杭电ACM OJ 1013 Digital Roots 如何用递归优雅地把一个未知长度的长整数的每一位拆分出来

Digital Roots

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 82266    Accepted Submission(s): 25781


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

翻译:就是39 3+9=12 1+2=3 他要的就是这个个位数,如果各个位数相加不是个位数,那就继续加,加到变成个位数为止

public class DigitalRoots1013 {

    public static void main(final String[] args) throws Exception {

        int result = calculate(396);

        System.out.println(result);
    }

    private static int calculate(int value) {
        //个位 value % 10
        //十位 ((value - value % 10) / 10) % 10
        //百位(如果存在) ((value - 个位 - 十位 * 10) / 100) % 10
        //没有规律性,所以思考方向不对了,换个思路
        //个位 value % 10 , value = (value - value % 10) / 10
        //十位 一样 传进来这样一个value依然可以当求各位一样求。。所以可以用递归了
        if (value < 10) {
            return value;
        }
        List list = new ArrayList<>();
        putLastToList(value, list);//这一步把list传进去,执行完后,list就取得了。
        int sum = 0;
        for (int i : list) {
            sum += i;
        }
        if (sum >= 10) {
            return calculate(sum);
        } else {
            return sum;
        }
    }

    private static void putLastToList(int value, List list) {
        if (value < 10) {
            list.add(value);
            return;
        }
        int p = value % 10;
        value = (value - value % 10) / 10;
        list.add(p);
        putLastToList(value, list);
    }
}

你可能感兴趣的:(算法题)