杭电1013(JAVA版)

该博客介绍了如何使用Java的BigInteger类来计算正整数的数字根。通过不断将数字的各位相加直到结果为一位数的过程,实现了数字根的计算。示例代码展示了从输入文件读取正整数,计算其数字根并输出结果。当遇到0时,表示输入结束。修正后的代码避免了数值溢出的问题,确保了正确性。
摘要由CSDN通过智能技术生成

Digital Roots

 
Problem Description
The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.

For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.
 
Input
The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.
 
Output
For each integer in the input, output its digital root on a separate line of the output.
 
Sample Input
24
39
0
Sample Output
6
3

原先的答案是

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        while(scanner.hasNext()) {
            int num=scanner.nextInt();
            if(num==0) break;
            while(num>=10) {
                int sum=0;
                String strNum=num+"";
                for(int i=0;i<strNum.length();i++) {
                    sum=sum+Integer.parseInt(strNum.charAt(i)+"");
                }
                num=sum;
            }
            System.out.println(num);
        }
        scanner.close();
    }
}

提示“Wrong Answer”,去结合了其他人的代码发现用的都是BigInteger,修改了代码再测试果然可以了。

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        while(scanner.hasNext()) {
            BigInteger num=scanner.nextBigInteger();
            if(num.compareTo(new BigInteger("0"))==0) break;
            while(num.compareTo(new BigInteger("9"))==1) {
                int sum=0;
                String strNum=num+"";
                for(int i=0;i<strNum.length();i++) {
                    sum=sum+Integer.parseInt(strNum.charAt(i)+"");
                }
                num=BigInteger.valueOf(sum);
            }
            System.out.println(num);
        }
        scanner.close();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值