ADD Digits
Given a non-negative integer num
, repeatedly add all its digits until the result have only one digit.
For example:
Givennum = 38
, the process is like:3 + 8 = 11
,1 + 1 = 2
. Since2
have only one digit, return it.
Follow up:
Could do it without any loop/recursion in O (1) runtime?
Problem Solving Ideas:
Solution One:
The simulation method constantly splits the numbers and then adds them until there is only one number.
Class Solution {public: int adddigits (int. num) { while (num/10>0) { int sum = 0; while (num!=0) { sum + = num%10; num = NUM/10; } num = sum; } return num; }};
Solution Two:
The topic requires no recursion, no loops, and a time complexity of O (1). Then find the rules.
~input:0 1 2 3 4 ... output:0 123456789123456789123....
Notice that the back is all 1-9 continuous loops.
There are two formulas:
D (n) = num%9 = = 0? (num==0 0:9): num%9
D (n) = 1 + (n-1)% 9
So the code looks like this:
Class Solution {public: int adddigits (int num) { return 1 + (num-1)%9; }};
Or:
Class Solution {public: int adddigits (int num) { return num%9 = = 0? (num==0?0:9): num%9; };
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] ADD Digits