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.
Subject to the effect :
Given a non-negative num, repeated seeking its digital sum, and to a digital, the digital output.
Understanding:
The current digital sum demand num num non-zero when the sum, if the sum is greater than equal to 10, num = sum is updated, the number continues to seek and num. To sum <10.
Method two : refer others to practice, to find the law. Num is assumed that three-digit number, the num = 100 * a + 10 * b + c. newNum = a + b + c. Difference dif = num - newNum = 99 * a + 9 * b, is a multiple of 9
I.e. num = newNum + dif. The newNum = num% 9. If newNum = 0, then num = 9.
Code C ++:
class solution { public : int addDigits ( int num) { int sum; while (I> = 10 ) { sum = 0 ; while (num) { sum + = (whether% 10 ); whether he / = 10 ; } Whether = I; } Return sum; } };
operation result:
When execution: 12 ms, beat the 74.46% of all users to submit in C ++