[LeetCode][Java] Excel Sheet Column Number

최지수·2022년 2월 23일
0

Algorithm

목록 보기
58/77
post-thumbnail

문제

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

제한사항

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

접근

Z - A, 즉 26진법으로 가정하고 접근해서 풀었어요. 그리고 각 한자리 숫자는 A에서 Z라는 숫자만 존재한다는 식으로 접근했고 간단하게 풀었어요.

답안

class Solution {
    
    public int titleToNumber(String columnTitle) {
        int answer = 0;

        for(int i = columnTitle.length() - 1, radix = 1; i >= 0; --i, radix *= (int)('Z' - 'A' + 1)){
            answer += (int)(columnTitle.charAt(i) - 'A' + 1) * radix;
        }

        return answer;
    }
}
profile
#행복 #도전 #지속성

0개의 댓글