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


  • 12
    class Solution(object):
        def addDigits(self, num):
            return num if num == 0 else num % 9 or 9

  • 0
    L

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

    Why not:

    return num if num <= 9 else num % 9
    

    ?


  • 0

    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


  • 0
    L

    Good point! Thanks for the explanation. I overlooked the situation where

    num % 9 == 0

  • 0
    V

    I am a little puzzled. Could you add parentheses in the code and explain what does your code mean?


  • 0
    P

    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
    

Log in to reply
 

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