Digital Roots

132 阅读2分钟

​题目描述

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.

正整数的数字根是通过对整数的数字求和而得出的。如果结果值是一个数字,那么该数字就是数字根。如果结果值包含两个或多个数字,则将这些数字相加并重复该过程。只要获得一位数字就可以继续进行。例如,考虑正整数24。将2和4相加得出6的值。由于6是单个数字,所以6是24的数字根。现在考虑正整数39。将3和9相加得出12.由于12不是单个数字,因此必须重复该过程。1和2相加得到3,一个个位数,也是39的数字根。

输入描述:

The input file will contain a list of positive integers, one per line. The integer may consist of a large number of digits.

输入文件将包含一个正整数列表,每行一个。整数可能包含大量数字

输出描述:

For each integer in the input, output its digital root on a separate line of the output.

对于输入中的每个整数,在输出的单独一行上输出其数字根。

示例1

输入

24
39
0

输出

6
3

思路:

主函数首先录入数据,然后将数据丢到NumRoot()里面去,在NumRoot()里面递归,最终回来的只有两种情况,要么返回了一个0~9的数,要么是0。

NumRoot()里,首先判断传进来的数是否是0~9,若是,则本身就是数根,已经得到结果,若不是0~9,则把它每个位上的数做求和运算,然后再判断这个sum,若sum是0~9则得到结果,若不是再进行一次NumRoot()

import java.util.Scanner;
 
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int x = sc.nextInt();//录入
 
            int result = NumRoot(x);    //计算
 
            //输出
            if (result > 0)
                System.out.println(result);
            else
                System.out.println();
        }
    }
 
    public static int NumRoot(int x) {
        int result;
        if (x > 0 && x < 10) result = x;    //如果只有一位,则本身就是数根
        else {
 
            //先求每个位上的数之和
            int sum = 0;
            while (x > 0) {
                sum += x % 10;
                x /= 10;
            }
 
            if (sum > 9) result = NumRoot(sum);     //若求出的数和仍不是一位,递归
            else result = sum;              //若求出的数和只有一位,则得到数根
        }
        return result;
    }
 
}