N

(Leet Code c++)Excel Sheet Column Number 본문

Leet Code 알고리즘

(Leet Code c++)Excel Sheet Column Number

naeunchan 2021. 7. 21. 11:22
728x90
반응형

171. Excel Sheet Column Number

 

Given a string columnTitle that represents the column title as appear 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

Example 4:

Input: columnTitle = "FXSHRXW" Output: 2147483647

 

Constraints:

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

 

class Solution {
public:
    int titleToNumber(string columnTitle) {
        int answer = 0;
        int length = columnTitle.size() - 1;
        
        for(int i = length; i >= 0; i--){
            int n = columnTitle[i] - 'A' + 1;
            
            answer += pow(26, length - i) * n;
        }
        
        return answer;
    }
};
728x90
반응형