Python approach using base 26


  • 0

    Using a base 26 (26 values between ord('Z') and ord('A') ) one could represent an input like so:

    ABA = ((26^2)*A) + ((26^1)*B) + ((26^0)*A) = (26*26*1) + (26*2) + 1 = 729

    hence, to calculate the corresponding excel number:

    class Solution:
        def calc_num(self, a, multiplier):
            base_val =  ord(a) - ord('A') + 1
            multiple = (ord('z')-ord('a')+1)**multiplier
            return base_val * multiple
        
        def titleToNumber(self, s):
            """
            :type s: str
            :rtype: int
            """
            result = 0        
            for i in range(len(s)):
                result += self.calc_num(s[len(s)-1-i], i)
            return result
    
    

Log in to reply
 

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