Help! Can anyone help me to find what is wrong?


  • 0
    O
    class Solution:
    # @param s, a string
    # @return an integer
    def titleToNumber(self, s):
        ret = 0
        i = 0
        while len(s) != 0 :
            tmp = s[len(s) - 1]
            ret += ord(tmp) - ord('A') + 1 + pow (26, i)
            s = s[:len(s) - 1]
            i += 1
        return ret
    

    Every time I run this code, it shows:
    "AA"
    output: 28
    expect: 27

    But, it is almost impossible that my code will output 28 for "AA".
    I have tried this code a thousand time in my local machine and its output is 27.

    I have no idea, this is really wired.


  • 0
    D

    You need to multiply instead of adding.

    ret += (ord(tmp) - ord('A') + 1)*pow(26,i)


  • 0
    O

    Yeah bro u r right. I realized this problem.


Log in to reply
 

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