Title Description: (link)
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?
Problem Solving Ideas:
1 classSolution {2 Public:3 intAdddigits (intnum) {4 stringCache =to_string (num);5 intresult =0;6 while(true) {7 for(Auto IX = Cache.begin (); IX! = Cache.end (); + +ix) {8Result + = (*ix-'0');9 } Ten One if(Result <=9) { A Break; - } -Cache =to_string (result); theresult =0; - } - returnresult; - } +};
Reprint Address: http://my.oschina.net/Tsybius2014/blog/497645
Assuming that the number entered is a 5 digit num, NUM's members are A, B, C, D, E, respectively.
Has the following relationship: num = A * 10000 + b * + + c * + + D * + E
That is: num = (A + B + C + D + E) + (A * 9999 + b * 999 + c * + D * 9)
Since A * 9999 + b * 999 + c * + D * 9 must be divisible by 9, the result of Num modulo 9 is the same as the result of a + B + C + D + E modulo except 9.
For the number A + B + C + D + E repeated execution of the same operation, the final result is a 1-9 number plus a string of numbers, the leftmost number is 1-9, the right side of the number will always be divisible by 9.
The final goal of this problem is to constantly add, add to the last, when the result is less than 10 o'clock return. Because the final result is between 1-9 and 9 will not be added to you, so there will not be a result of 0. Because (x + y)% Z = (x% z + y% z)% Z, and because X is z% z = x% Z, the result is (num-1)% 9 + 1, modulo only 91 times, and returns the result after modulo is added.
1 class Solution {2public:3 int adddigits (int num) {4 return19 1 ; 5 }6 };
[Leetcode] ADD Digits