class Solution(object): def addDigits(self, num): return num if num == 0 else num % 9 or 9
That's indeed an elegant way of putting the if/else statement in oneline.
return num if num <= 9 else num % 9
because you should return 9 when
e.g. 18, 27, 36, ... n * 9
btw, you can also write
num if num == 0 else num % 9 or 9 as
num and (num % 9 or 9) or num
num <= 9 and num or num % 9 or 9
num if num <= 9 else num % 9 or 9
Good point! Thanks for the explanation. I overlooked the situation where
num % 9 == 0
I am a little puzzled. Could you add parentheses in the code and explain what does your code mean?
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.