티스토리 뷰
Question
Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.
Excel 시트에 나타나는 열 제목을 나타내는 문자열 columnTitle이 주어지면 해당 열 번호를 반환합니다.
제약사항
- 1 <= columnTitle.length <= 7
- columnTitle consists only of uppercase English letters.
- columnTitle is in the range ["A", "FXSHRXW"].
Solution
문제를 풀 때 고려한 사항
- 문자는 대문자만 나옴.
- FXSHRXW가 마지막 문자인 것을 보니 int범위의 최댓값이 아닐까라는 추측이 듦
Solution1
간단하게 예를 들어서 생각해본다.
1자리 수 => 1 ~ 26, 총 26개
2자리 수 => 27 ~ 702, 총 676개 = 26²개
3자리 수 => 703 ~ 18278, 총 17576개 = 26³
그렇다면 26개의 단위로 column number를 확인할 수 있을 것 같다. 예를 들어,
a = 1
b = 2
c = 3
"ABC" 라면
'C' = 'C' - 'A' + 1
'B' = ('B' - 'A' + 1) * 26;
'A' = ('A' - 'A' + 1) * (26²)
로 세 수를 더하면 column number이다.
class Solution {
public:
int titleToNumber(string columnTitle) {
int ans_col = 0; // return 할 column 값
int str_len = columnTitle.length(); // 문자열의 길이
int back = str_len - 1; // 문자열의 뒤부더 탐색
int base_num = 0; // base_num을 기준으로 얼마나 26을 곱할지
while(back >= 0){ // 문자열 맨 앞까지 탐색
// 기준 수를 기준으로 얼마나 26을 곱할지 계산하는 부분
int copy_base_num = base_num;
int mul = 1;
while(copy_base_num--){
mul *= 26;
}
ans_col += (columnTitle[back] - 'A' + 1) * mul;
if(mul == 1) mul--;
base_num++;
back--;
}
return ans_col;
}
};
- Time complexity : O(n)
- Space Complexity : O(1)
출처 : https://leetcode.com/explore/interview/card/top-interview-questions-medium/113/math/817/
Explore - LeetCode
LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.
leetcode.com
'IT > Problem Solving' 카테고리의 다른 글
[C++] LeetCode : Sqrt(x) (0) | 2022.08.15 |
---|---|
[C++] LeetCode : Pow(x, n) (0) | 2022.08.15 |
[C++] LeetCode : Happy Number (0) | 2022.08.14 |
[C++] LeetCode : Factorial Trailing Zeros (0) | 2022.08.14 |
[C++] LeetCode : Merge Interval (0) | 2022.08.10 |
- Total
- Today
- Yesterday
- PS
- rust
- 인터뷰
- 알고리즘
- 리트코드
- 속초 맛집
- Tree
- 러스트 입문
- C++
- 러스트 배우기
- LeetCode
- 맛집
- 속초
- Interview
- 트리
- DP
- Medium
- 반드시 알아야 할 자료구조
- 내돈내산
- coding interview
- interview question
- 솔직후기
- ProblemSolving
- 러스트
- 러스트 기초
- 자료구조
- algorithm
- Problem Solving
- 코딩인터뷰
- 기술면접
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |