Welcome to Subscribe On Youtube

Question

Formatted question description: https://leetcode.ca/all/171.html

Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.

For example:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28 
...

 

Example 1:

Input: columnTitle = "A"
Output: 1

Example 2:

Input: columnTitle = "AB"
Output: 28

Example 3:

Input: columnTitle = "ZY"
Output: 701

 

Constraints:

  • 1 <= columnTitle.length <= 7
  • columnTitle consists only of uppercase English letters.
  • columnTitle is in the range ["A", "FXSHRXW"].

Algorithm

It is equivalent to a problem of converting from hexadecimal to decimal. It is not difficult, as long as the conversion is bit by bit.

Code

  • 
    public class Excel_Sheet_Column_Number {
        class Solution {
            public int titleToNumber(String s) {
                int result = 0;
    
                for (int i = 0; i < s.length(); i++) {
                    result = result * 26 + (s.charAt(i) - 'A' + 1);
                }
    
                return result;
            }
        }
    }
    
    ############
    
    class Solution {
        public int titleToNumber(String columnTitle) {
            int res = 0;
            for (char c : columnTitle.toCharArray()) {
                res = res * 26 + (c - 'A' + 1);
            }
            return res;
        }
    }
    
  • // OJ: https://leetcode.com/problems/excel-sheet-column-number/
    // Time: O(N)
    // Space: O(1)
    class Solution {
    public:
        int titleToNumber(string s) {
            int ans = 0;
            for (char c : s) ans = ans * 26 + (c - 'A' + 1);
            return ans;
        }
    };
    
  • class Solution:
        def titleToNumber(self, columnTitle: str) -> int:
            res = 0
            for c in columnTitle:
                res = res * 26 + (ord(c) - ord('A') + 1)
            return res
    
    ############
    
    class Solution(object):
      def titleToNumber(self, s):
        """
        :type s: str
        :rtype: int
        """
        letters = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "H": 8, "I": 9, "J": 10, "K": 11, "L": 12,
                   "M": 13, "N": 14, "O": 15, "P": 16, "Q": 17, "R": 18, "S": 19, "T": 20, "U": 21, "V": 22, "W": 23,
                   "X": 24, "Y": 25, "Z": 26}
        s = s.upper()
        ret = 0
        b = 0
        for c in reversed(s):
          ret += letters[c] * 26 ** (b)
          b += 1
        return ret
    
    
  • func titleToNumber(columnTitle string) int {
    	res := 0
    	for _, c := range columnTitle {
    		res = res*26 + int(c-'A'+1)
    	}
    	return res
    }
    
  • function titleToNumber(columnTitle: string): number {
        let res: number = 0;
        for (let char of columnTitle) {
            res = res * 26 + char.charCodeAt(0) - 64;
        }
        return res;
    }
    
    

All Problems

All Solutions