SGU118 Digital Root

SGU118 Digital Root

题目大意

V=A1A2AN+A1A2AN1++A1A2+A1
每次将V变为V的数位和,直至V小于10,输出这时V的值

算法思路

直接计算出V的初始值,然后模拟上述过程
使用Java的BigInteger类可以避免手动实现高精度运算

时间复杂度: O(N)

代码

/** * Copyright (c) 2015 Authors. All rights reserved. * * FileName: 118.java * Author: Beiyu Li <[email protected]> * Date: 2015-05-23 */
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;

public class Solution {
    public static void main(String args[])
    {
        Scanner cin = new Scanner(new BufferedInputStream(System.in));
        int T = cin.nextInt();
        while (T-- > 0) {
            int n = cin.nextInt();
            BigInteger s = BigInteger.ZERO, p = BigInteger.ONE;
            for (int i = 0; i < n; ++i) {
                int v = cin.nextInt();
                s = s.add(p = p.multiply(BigInteger.valueOf(v)));
            }
            int val = 0;
            String str = s.toString();
            for (int i = 0; i < str.length(); ++i)
                val += str.charAt(i) - '0';
            while (val >= 10) {
                int t = val; val = 0;
                while (t > 0) { val += t % 10; t /= 10; }
            }
            System.out.println(val);
        }
    }
}

你可能感兴趣的:(BIgInteger,sgu)