HDOJ1013 Digital Roots

来源:互联网 发布:文字播音软件 编辑:程序博客网 时间:2024/05/19 17:59

题目链接:Digital Roots

给出一个正整数,然后将该整数的每一位加起来,如果是只有个位数,就输出。

如果还大于10,就继续将每一位加起来,直到只有个位数。

但是值得注意的是,题目没讲整数的范围,所以应该是使用大数BigInteger的。

下面AC代码:

import java.math.BigInteger;import java.util.Scanner;public class Main{private static Scanner scanner;public static void main(String[] args) {scanner = new Scanner(System.in);while(scanner.hasNext()){String string = scanner.next();if(string.equals("0")){break;}BigInteger n = new BigInteger(string);BigInteger ten = new BigInteger(""+10);BigInteger zero = new BigInteger(""+0);while(n.compareTo(new BigInteger(""+9))>0){//这里注意,是大于9,因为是两位数BigInteger vol = n;BigInteger sum = zero;while(vol.compareTo(zero)>0){//大于零就要继续加//sum += vol%10;//vol /= 10;sum = sum.add(vol.remainder(ten));vol = vol.divide(ten);}          //System.out.println(sum);n = sum;}System.out.println(n);}}}/*                        //这里是WA的,应该使用上面的大数的方法。                       while(scanner.hasNext()){int n = scanner.nextInt();if(n == 0){break;}while(n>=10){int vol = n;int sum  = 0;while(vol>0){sum += vol%10;vol /= 10;}n = sum;}System.out.println(n);*/



原创粉丝点击