Explanation in Python

  • 8

    Observe that this is basically the same thing as converting between base 26 and base 10.

    Start with this:

    def titleToNumber(s):
        s = s[::-1]
        sum = 0
        for exp, char in enumerate(s):
            sum += (ord(char) - 65 + 1) * (26 ** exp)
        return sum

    This reverses the string, starts a sum at 0, creates a list of tuples of the index of each character in the reversed string (which corresponds to the exponent) and character itself. Add them up. We take ord(char) to turn the character to an integer, subtract 65 = ord('A') from it, and add one because we want A to equal 1, not 0.

    You can do this in one line:

    def titleToNumber(s):
        return sum((ord(char) - 64) * (26 ** exp) for exp, char in enumerate(s[::-1]))

  • 0

    Smart solution! Thanks for sharing!

Log in to reply

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