Tuesday, November 10, 2015

Add Digits

Q:
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.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?

A:

----------递归+循环
class Solution {
public:
    int addDigits(int num) {
       
        while(num >= 10)
        {
            int res = 0;
            while(num > 0)
            {
                res += num %10;
                num /= 10;
            }
            num = res;
        }
        return num;
    }
};
-----------------每次进位的时候,其实都是在下次的值上增加了1—————————

public class Solution {
    public int addDigits(int num) {
        int s = 0;
        while(num !=0){
            s += num%10;
            if(s>=10)
                s = s%10  +1;
            num /= 10;
        }
        return s;
    }
}

***********************一行代码,的解法 *******************************
class Solution {
public:
    int addDigits(int num) {
       return 1+((num-1)%9);
    }
};
下面这个也是:

public int addDigits(int num) {
    return num == 0 ? 0 : (num % 9 == 0 ? 9 : num % 9);
}



No comments:

Post a Comment