# 1 line Java Solution

• ``````public class Solution {

public int addDigits(int num) {

return num==0?0:(num%9==0?9:(num%9));

}

}``````

• We have exactly the same solution!

• Please explain how did you figure that out?

• you can find more details on

https://en.wikipedia.org/wiki/Digital_root

check the congruence formula.

:)

• Is this a kind of recursive?

• Brilliant 1 liner...
Nope, it does not use recursion.
It is based on the mathematical property of congruence. The Digital Root of a number is same as the remainder when that number is divided by 9 (and this remainder will always be a single digit). Thus you get result just after one modulo operation over num, no need of any recursion then.

• This post is deleted!

• Explain, take 438 as an example

[Step 1]:

``````438  == 40*10 +3*10 +8 ;

4+3+8 == 4*(10%9)*(10%9)+3*(10%9)+8%9= 15   ;
``````

[Step 2]:

``````15  == 1*10 + 5 ;

1+5 == 1*(10%9)+5%9= 6 ;
``````

[So we can see]:

``````ab%9%9%9==ab%9;

just return num%9; and don't forget num==0 or num==9   ``````

• ``````public int addDigits(int num) {
return 1 + (num - 1) % 9;
}
``````

A real one line solution!

• @brl2014 What if num = 0

• @mani89 1 + (0-1)%9 = 1 + (-1) = 0 //base case taken care off

• @hangbo Thanks

• Mathematics always make me have a headache...

• @hangbo I have a stupid question. Why should we consider num==0? I mean if num==0, then 0%9==0. So num%9 includes num==0 situation. Thus we can only consider two situations which are num%9 and num==9. Right? I don't know what's wrong with my idea.

• @Everestsky 0 % 9 == 0 and 9n %9 == 0, we need to distinguish 0 and 9n.(0 return 0 and 9n return 9)

• @carlislelee well,actually,you do not need to deliberately pursue one-line code,as it makes the code seem less concise ,and this is my code:

``````public class Solution {
public int addDigits(int num) {
if(num==0)return 0;
return num%9==0?9:num%9;
}
}
``````

• @wanqing life is so hard :<

• @carlislelee Thats a grate logic. Why did you decide to divide by 9. What not any another other number.I am curious to know.

• @mani89 if(num==0)return 0;
return 1 + (num - 1) % 9;

• @Everestsky Not a stupid question, don't worry. The problem is that the main operation being preformed is num % 9. This is only done if the remainder is not equal to 0. The number 18 as an input should not output 0, but should instead output 9. That is why there is the exception for on the inner set of parenthesis. If the input number is 0, there the check of (num % 9 ==0) would also be true, defaulting to that exception of needing to output 9 I mentioned. So to account for these two spots, you create two exceptions to your rule of mod 9: if the input is divisible by 9, and if the input itself is 0.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.