[LeetCode]258. Add Digits

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 = 111 + 1 = 2. Since 2 has only one digit, return it.


class Solution {
public:
    int addDigits(int num) {
        //例如123 = 1*(99+1) + 2*(9+1) +3,算法要做的就是把9的倍数那一项删除
        //用-1  +1的方式规避某项为9的问题
        return (num - 1) % 9 + 1;
    }
};


你可能感兴趣的:(LeetCode)