Computer Science/알고리즘

leetcode 171) Excel Sheet Column Number

eeeun:) 2022. 2. 22. 12:12
반응형

LV. Easy 😎

https://leetcode.com/problems/excel-sheet-column-number/

 

Excel Sheet Column Number - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

문제

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

 

Constraints:

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

 

문제 해결법

26진수이다!

10진법을 계산하는 것과 동일하게 한 자릿수가 올라갈 때마다 *26을 해주면 된다.

 

해결 코드
class Solution {
public:
    int titleToNumber(string columnTitle) {
        int ans = 0;

        for (int i = 0; i < columnTitle.size(); ++i) {
            int temp = columnTitle[i] - 64;
            ans = ans * 26 + temp;
        }
        return ans;
    }
};

728x90