Given a non-negative integer num
, repeatedly add all its digits until the result have only one digit.
For example:
Given num = 38
, the process is like: 3 + 8 = 11
, 1 + 1 = 2
. Since have only one 2
digit, return it.
Follow up:
Could do it without any loop/recursion in O (1) runtime?
Train of thought: if the complexity is not required, through the conventional algorithm, constantly on the 10 redundancy and the addition of 10, step by step with the For loop to add the results can be obtained. But the problem requires not to cycle, after watching a few hint, feel regular, but still can not find out the specific formula, later read the formula in the Wiki encyclopedia, found that is 1-9 continuous cycle, the problem becomes very simple, add up the number can be attributed to a formula, after the code is very simple.
My Code:
class Solution {public: int adddigits (int num) { int 1 + (num-1)%9; return s; }};
Reference code:
classSolution { Public: intAdddigits (intnum) { Switch(Random ()%5+1){ Case 1:returnaddDigits01 (num); Case 2:returnaddDigits02 (num); Case 3:returnaddDigits03 (num); Case 4:returnaddDigits04 (num); default:returnaddDigits05 (num); } } //regualr intADDDIGITS01 (intnum) { while(Num >9) { intsum; for(sum=0; num >0; Sum + = num%Ten, num/=Ten); Num=sum; } returnnum; } //This solution looks was very tricky, but acutally it was easy to understand. //it just keep adding the last digital until the NUM < intADDDIGITS02 (intnum) { while(Num >9) {num= num/Ten+ num%Ten; } returnnum; } //Let ' s observe the pattern//1 1//2 2// ... ... //8 8//9 9//Ten 1//2//3// ... ... //8//9//1//2// ... ... //It looks most of number just simply%9 are the answer,//But there is some edge cases. //9%9=0 but we need 9. //18%9=0 But we need 9//So we can find the solution is://1) Num <=9, return num//2) num > 9, reutrn num%9 if num%9>0//return 9 if num%9 ==0 intADDDIGITS03 (intnum) { returnnum >9? (num%9)==0?9: num%9): num; } //but actually, we can use (num-1)%9 + 1 to make all cases right. intAddDigits04 (intnum) { return(Num-1) %9+1; } //This solution are similar with pervious solution. intADDDIGITS05 (intnum) { returnNum-9* (Num-1)/9); }};
Summary: The reference code is complete to show the process from the general algorithm to the simplest algorithm, under two or three conditions to judge, learn the code in the reference:
Return num >9? (num%9) ==0 9:num%9): num;
When there are multiple algorithms for the same problem, the combination of Switch+random () is fun, haha:
Switch (random ()%5+1)
258.ADD Digits