Python solution - int to string then string to int


  • 0
    J
    def addDigits(self, num):
       
        numstr = str(num)
        nnumA = {}
    
        if len(numstr) > 1:
            while len(numstr) > 1:
                sum1 = 0
                for i in range(len(numstr)):
                    nnumA[i] = int(numstr[i])
                    sum1 = sum1 + nnumA[i]
    
                numstr = str(sum1)
        else:
            sum1 = num
    
        return sum1
    

    I just started to learn python few months ago, and it seems this is a different approach from other's solution.

    I got accepted with this method, so I guess this does not have a problem, but I am wondering if there are any reasons people do not approach in this way.


  • 0
    Q

    @jyeon89

    A shorter one:

    def addDigits(self, num):
        while num >9:
            sn,num=str(num),0
            for i in sn:num+=int(i)
        return num

  • 0
    J

    @QGB

    It does not work :(


  • 0
    J

    @QGB

    It says:
    NameError: global name 'Solution' is not defined

    However, it works on my python shell.


  • 0
    J

    @QGB

    Oh... Never mind.. I found it out.

    Thank you!!


Log in to reply
 

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