public class Solution {
public int addDigits(int num) {
return num==0?0:(num%9==0?9:(num%9));
}
}
1 line Java Solution

you can find more details on
https://en.wikipedia.org/wiki/Digital_root
check the congruence formula.
:)

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.




@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 oneline 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; } }


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


@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.