给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。
示例:
输入: 38输出: 2解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。
进阶:
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?
循环求解
class Solution {public:int addDigits(int num) {int res = num;while(res>9){num = res;res = 0;while(num>0){res += num %10;num = num / 10;}}return res;}};
数学取余法
所以我们可得
class Solution {
public:
    int addDigits(int num) {
        return (num - 1) % 9 + 1;
    }
};
                    