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.

Follow up:

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

把一個數拆成單個,相加,直到加結果爲個位數。

解析在不考慮複雜度的情況下,可以使用模擬法循環。

class Solution {
public:
    int addDigits(int num) {
        int result =10;
        if(num/10 == 0)
            return num;
        while(result/10 !=0){
            //num = result;
            result = 0; 
            while(num/10 != 0){
                result = result + num%10;
                num /= 10;
            } 
            result += num;
            if(result/10 !=0)
        	    num = result;
        }
        return result;
    }
};
在考慮的情況下,找到其規律:(num-1) % 9 + 1,

直接找需要一些數論的知識見:http://my.oschina.net/Tsybius2014/blog/497645

public class Solution {
    public int addDigits(int num) {
       return (num-1) % 9 + 1;
    }
}
發佈了46 篇原創文章 · 獲贊 22 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章