leetcode258題 題解 翻譯 C語言版 Python版
阿新 • • 發佈:2019-01-04
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 = 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?
258.加數字
給你一個非負整數num,重複把他的各位數字相加直到最後的結果只有一位數字。
例如:
給定num=38,這個過程就像:3+8=11, 1+1=2. 因為2只有一個數字,就返回他。
進一步的:
你能不用任何的迴圈和遞歸併且在O(1)的時間複雜度中完成嗎?
思路:對於任意整數abcde...,對其某一位i,如果將i抽離出來視作個位數,拋棄了他的權重,這個過程是可以分解成重複減9的行為的。例如14,對十位數1來說,原先表示的是10,抽離出來後表示為1,這個過程是減9。那麼34就可以看成3次減9。那麼345呢?百位的3先抽離到十位,是減9的重複,再抽離到個位,也是減9的重複。所以總的來說,模9就是題目所述的操作的簡化。不太一樣的是,模9得到的結果是0-8,而題目中除0以外任何數經題目操作後得到的結果應該是1-9.所以如果模9後得到的是0那麼應該改為9.
int addDigits(int num) {
if (num==0) return 0;
int i = num%9;
return i==0?9:i;
}
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
if num == 0:return 0
i = num % 9
return i if i != 0 else 9