LeetCode: Add Digits | CrazyEgg
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
http://shibaili.blogspot.com/2015/08/day-121-264-ugly-number-ii.html
http://blog.csdn.net/ER_Plough/article/details/48157351
Read full article from LeetCode: Add Digits | CrazyEgg
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?
Could you do it without any loop/recursion in O(1) runtime?
- A naive implementation of the above process is trivial. Could you come up with other methods?
- What are all the possible results?
- How do they occur, periodically or randomly?
- You may find this Wikipedia article useful.
public int addDigits(int num) { while (num > 9) { num = getInt(num); } return num; } private int getInt(int num) { int result = 0; while (num >= 10) { result += num % 10; num /= 10; } result += num; return result; }http://www.cnblogs.com/maples7/p/4734300.html
http://shibaili.blogspot.com/2015/08/day-121-264-ugly-number-ii.html
int
addDigits(
int
num) {
if
(num == 0)
return
0;
return
num - (num - 1) / 9 * 9;
}
http://blog.csdn.net/ER_Plough/article/details/48157351
给定一个整数,计算各位上的数字的和得到另外一个数字,直到该数字为个位数。
模拟一下就可以得出结果,但是要求o(1)的时间复杂度,找规律!
int addDigits(int num) { return 1+(num-1)%9; }
解法二、套公式digital root
int addDigits(int num) { return num - 9 * floor((num - 1) / 9); }
Read full article from LeetCode: Add Digits | CrazyEgg