letecode [258] - Add Digits

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

Example:

Input: 38
Output: 2 
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 
             Since 2 has only one digit, return it.

题目大意

  给定一个非负数num,重复的求它的数字之和,至和为一个数字,输出该数字。

理  解:

  当num非0时求当前num数字之和sum,若sum大于等于10,则更新num = sum,继续求num的数字之和。至sum<10。

  方法二:参考他人做法,寻找规律。假设num是个三位数,则num = 100*a + 10*b + c 。newNum = a + b + c。差值 dif = num - newNum = 99*a +9*b,为9的倍数

      即 num = newNum + dif 。则 newNum = num%9。  若newNum=0,则num = 9。

代 码 C++:

class Solution {
public:
    int addDigits(int num) {
        int sum;
        while(sum>=10){
            sum = 0;
            while(num){
                sum += (num%10);
                num /= 10;
            }
            num = sum;
        }
        return sum;
    }
};

运行结果:

  执行用时 :12 ms, 在所有C++提交中击败了74.46%的用户

  内存消耗 :8.3 MB, 在所有C++提交中击败了5.16%的用户
posted @ 2019-06-14 17:47  lpomeloz  阅读(85)  评论(0编辑  收藏  举报