LandscapeMi

landscapemi的博客

leetcode:数学:Add Digits(258)

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.


class Solution {
public:
    int addDigits(int num) {
        int sum = getSum(num);
        while (sum >= 10) {
            sum = getSum(sum);
        }
        return sum;
    }
private:
    int getSum(int num) {
        int sum = 0;
        while (num) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }
};
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mijian1207mijian/article/details/52369972
个人分类: leetcode(c++)
上一篇leetcode:数学:Number of Digit One(233)
下一篇leetcode:数学:Ugly Number(263)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭