1. 程式人生 > >[LeetCode] Add Digits

[LeetCode] Add Digits

could 進行 style 使用 pro out urn ati do it

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.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

給定一個非負整數,重復相加它的各個數位上的值直到這些數的和為1位數。按照題意使用while進行循環即可。

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

[LeetCode] Add Digits