# No loop/recursion, O(1) runtime, just one line python code

• ``````class Solution(object):
return num if num == 0 else num % 9 or 9``````

• That's indeed an elegant way of putting the if/else statement in oneline.

Why not:

``````return num if num <= 9 else num % 9
``````

?

• because you should return 9 when `num=n*9`
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):
if num == 0:
return 0
elif num % 9 == 0:
return 9
else:
return num % 9
``````

• @shiyanhui
Thank you very much, I got it immediatly

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