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?
Not OP but it's essentially this but a lot more concise.
class Solution(object): def addDigits(self, num): if num == 0: return 0 elif num % 9 == 0: return 9 else: return num % 9
Thank you very much, I got it immediatly
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.