Python solution


  • 0
    R

    Simple mathematical solution. The way we calculate the value of a number using units and tens places.
    eg : 121 = 1* 10^2 + 2* 10^1 + 1* 10^0
    Similarly : AB = A26^1 + B26^0. Here base is taken as 26 instead of 10. and replace the value of A-Z as 1-26.

    import string
    import math
    class Solution(object):
        def getDictionary(self):
            D = {}
            for i , alphabet in enumerate(string.ascii_uppercase):
                D[alphabet] = i+1
            return D
            
        def titleToNumber(self, s):
            """
            :type s: str
            :rtype: int
            """
            alphabtes =  self.getDictionary()
            sum = 0
            for i , a in enumerate(s[::-1]):
                val = alphabtes[a] * (math.pow(26,i))
                sum = sum + val
            return int(sum)

Log in to reply
 

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