題目描述:
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?
Hint:
A naive implementation of the above process is trivial. Could you come up with other methods?
題目大意:
給定一個(gè)非負(fù)整數(shù)num鳞芙,重復(fù)地將其每位數(shù)字相加谷暮,直到結(jié)果只有一位數(shù)為止椎眯。
例如:
給定 num = 38欲芹,過程像這樣:3 + 8 = 11, 1 + 1 = 2丁逝。因?yàn)?只有一位尔崔,返回之勤婚。
進(jìn)一步思考:
你可以不用循環(huán),在O(1)運(yùn)行時(shí)間內(nèi)完成題目嗎臣疑?
提示:
一個(gè)直觀的解法就是模擬上述過程盔憨。你可以想到別的方法嗎?
結(jié)果一共有多少種可能性讯沈?
它們是周期性出現(xiàn)的還是隨機(jī)出現(xiàn)的郁岩?
解題思路:
觀察法
根據(jù)提示,由于結(jié)果只有一位數(shù)缺狠,因此其可能的數(shù)字為0 - 9
使用方法I的代碼循環(huán)輸出0 - 19的運(yùn)行結(jié)果:
in out in out 0 0 10 1 1 1 11 2 2 2 12 3 3 3 13 4 4 4 14 5 5 5 15 6 6 6 16 7 7 7 17 8 8 8 18 9 9 9 19 1
可以發(fā)現(xiàn)輸出與輸入的關(guān)系為:
out = (in - 1) % 9 + 1
C++代碼:
class Solution { public: int addDigits(int num) { return (num-1)%9+1; } };