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.
The problem is to find the number root of a number.
The number root has a congruence property: A number with its number root pair (b-1) congruence (b is the binary number).
A simple example of this is clear:
123=1*100+2*10+3
=1* (99+1) +2* (9+1) +3
= (99+2*9) + (1+2+3)
The previous item can be divisible by 9, and the next one is the number of each bit. The number that is obtained after the 1+2+3, still can be so split, go down until the number root.
Therefore a number with its number root pairs (b-1) congruence (b is the binary number).
For the subject, we use this property for the number of roots, because the number of roots is a number, and the number of%9 and num%9 results the same, so we are directly num%9, but the number we find here is not number root, the number is [0,9], and%9 to find out is [1,8], So we add a small processing technique: minus 1 First, and then add 1 after the mold.
class Solution {public: int adddigits (int num) { return1+ (num-1)%9; }};
Leetcode 258. Add Digits (number theory)