LeetCode #258. Add Digits

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 = 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,過(guò)程像這樣:3 + 8 = 11, 1 + 1 = 2。因?yàn)?只有一位,返回之。
進(jìn)一步思考:
你可以不用循環(huán),在O(1)運(yùn)行時(shí)間內(nèi)完成題目嗎?
提示:
一個(gè)直觀的解法就是模擬上述過(guò)程。你可以想到別的方法嗎?
結(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; } };

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容