258. Add Digits 數位相加到只剩一位數
阿新 • • 發佈:2018-05-01
異常 return b- 空間 rep 題目 corn ret dig
[抄題]:
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.
[暴力解法]:
時間分析:
空間分析:
[優化後]:
時間分析:
空間分析:
[奇葩輸出條件]:
[奇葩corner case]:
[思維問題]:
[一句話思路]:
%9
[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):
[畫圖]:
[一刷]:
if + else if不是完整的,if + else才是完整的
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分鐘肉眼debug的結果]:
[總結]:
if + else if不是完整的,if + else才是完整的
[復雜度]:Time complexity: O(1) Space complexity: O(1)
[英文數據結構或算法,為什麽不用別的數據結構或算法]:
[關鍵模板化代碼]:
[其他解法]:
[Follow Up]:
[LC給出的題目變變變]:
[代碼風格] :
class Solution { public int addDigits(int num) { if (num == 0) return 0; if (num % 9 == 0) { return 9; } else{ return num % 9; } } }View Code
258. Add Digits 數位相加到只剩一位數