Excel Sheet Column Number Problem


Description

LeetCode Problem 171.

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

For example:

1
2
3
4
5
6
7
8
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28 
...

Example 1:

1
2
Input: columnTitle = "A"
Output: 1

Example 2:

1
2
Input: columnTitle = "AB"
Output: 28

Example 3:

1
2
Input: columnTitle = "ZY"
Output: 701

Example 4:

1
2
Input: columnTitle = "FXSHRXW"
Output: 2147483647

Constraints:

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


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
    int titleToNumber(string s) {
        int n = s.size();
        if (n == 0)
            return 0;
        int ans = 0;
        for (int i = 0; i < n; i ++) {
            ans *= 26;
            ans += s[i] - 'A' + 1;
        }
        return ans;
    }
};




Related Posts

String Without Aaa Or Bbb Problem

LeetCode 984. Given two integers a and b, return any...

Shifting Letters Problem

LeetCode 848. You are given a string s of lowercase...

Positions Of Large Groups Problem

LeetCode 830. In a string sof lowercase letters, these letters...

Orderly Queue Problem

LeetCode 899. You are given a string s and an...

Number Of Lines To Write String Problem

LeetCode 806. You are given a string s of lowercase...

Masking Personal Information Problem

LeetCode 831. You are given a personal information string s,...