Leetcode original title Link: https://leetcode.com/problems/add-digits/
Given a non-negative integer num, repeatedly add all it digits until the result has only one digit.
For example:
Given num =, the process is Like:3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit and return it.
Follow up:
Could it without any loop/recursion in O (1) runtime?
Brief translation:
Given a non-zero integer num, repeat the number on the sum to know that there is only one digit position.
For example, given the number 38, the run result is 3+8 = 11, 1+1 = 2. Because 2 has only one digit, it returns 2.
Requirement: Complete the calculation in O (1) Run time without the help of loops and recursion.
Brief analysis:
The topic asks, does not use the cycle and the recursion premise, solves this problem.
Based on the experience, I wrote the following code:
public static int adddigits (int num)
{
num = sumdigits (num);
if (Num <) return
num;
else return
adddigits (num);
}
private static int sumdigits (int num)
{
if (num <) return
num;
else return
sumdigits (NUM/10) +num%10;
}
This code is AC. But I am careful, not ah ... I use recursion here.
So while AC is, it's actually wrong.
There is another way to solve this problem.
So let's try a couple of numbers and try to find the rules ...
Input: 1,2,3,4,5,6,7,8,9,10 11, 12, 13, 14, 15, 16, 17, 18, 19,20 results: 1, 2,3,4,5,6,7,8,9,1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2
According to the above attempt, we can find that there is a regular.
The result is satisfied, (num-1)%9+1
So you have the following code:
public static int adddigits (int num)
{return
(num-1)%9+1;
}
The answer is the correct answer to AC ...