Title Description:
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.
Problem Solving Ideas:
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, so the result is (num-1)% 9 + 1, modulo only 91 times, and add a return after modulo the result
The code is as follows:
public class Solution {public int adddigits (int num) { return (num-1)% 9 + 1; }}
Java [Leetcode 258]add Digits