Post

[LeetCode 171] Excel Sheet Column Number

LeetCode 171 (Java)
[Excel Sheet Column Number] 문제 풀이

[LeetCode 171] Excel Sheet Column Number

문제 바로가기


Description


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


  • 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"].







Code


내 제출


1
2
3
4
5
6
7
8
9
10
class Solution {
    public int titleToNumber(String columnTitle) {
        int ans = 0;
        for (int i = 0; i < columnTitle.length(); ++i) {
            ans = ans * 26 + (columnTitle.charAt(i) - 'A' + 1);
        }
        return ans;
    }
}


RuntimeMemory
1 ms42.3 MB


다른 풀이


1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
    public int titleToNumber(String columnTitle) {
        int result = 0;
        for (int i = 0; i< columnTitle.length(); i++){
            char c = columnTitle.charAt(i);
            int value = c - 'A' + 1;
            result = result * 26 + value;
        }
        return result;
    }
}


Reference


  • https://github.com/doocs/leetcode/blob/main/solution/0100-0199/0171.Excel%20Sheet%20Column%20Number/Solution.java
This post is licensed under CC BY 4.0 by the author.