LeetCode258题:各位相加——数字根

版权声明:本文为博主原创文章,转载请注明出处! https://blog.csdn.net/ASN_forever/article/details/84966900

这道题涉及到数学领域的一个定理,即“数字根”。

解法一:笨方法(循环)

public int addDigits(int num) {
        Integer res = new Integer(num);
        while(res>9){
            String str = res.toString();
            int temp = 0;
            for(int i=0;i<str.length();i++){
                temp+=Integer.parseInt(str.substring(i,i+1));
            }
            res = new Integer(temp);
        }
        return res;
    }

解法二:公式法

public int addDigits(int num) {
        return (num-1)%9+1;
    }

猜你喜欢

转载自blog.csdn.net/ASN_forever/article/details/84966900