LeetCode 258 Add Digits
题目:
Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
Example:
Input:38
Output: 2 Explanation: The process is like:3 + 8 = 11
,1 + 1 = 2
. Since2
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) { while(num>9) { int newnum = 0; while(num>0) { newnum += num%10; num /= 10; } num = newnum; } return num; } }
但题目中的额外要求,在不使用循环的O(1)时间复杂度下完成
class Solution { public int addDigits(int num) { if(num==0) return 0; return (num%9==0)?9:(num%9); } }
为什么可以通过对9求模得出结果,解释如下:
以2345为例
2345 = 2(1+999)+ 3(1+99)+4(1+9)+5
则
2345%9 = (2+3+4+5)%9 = 14%9
再讲14同理推导一遍,最后就能得到结果。通过模9,就能将循环过程省略从而直接得到结果。