关闭

leetcode:数学:Add Digits(258)

157人阅读 评论(0) 收藏 举报
分类:

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;
    }
};
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:123535次
    • 积分:6897
    • 等级:
    • 排名:第3498名
    • 原创:589篇
    • 转载:2篇
    • 译文:0篇
    • 评论:2条
    最新评论