Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Array
- sorting
- DP
- 이진트리
- recursive
- 쉬움
- 재귀
- 미디움
- tree
- Medium
- HashTable
- hash table
- 중간
- dfs
- 리트코드
- easy
- Depth-first Search
- binary tree
- two pointers
- leetcode
- linked list
- Binary
- string
- backtracking
- math
- 문자열
- matrix
- list
- binary search
- Python
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 171(Excel Sheet Column Number, Python) 본문
1. 문제 링크
Excel Sheet Column Number - LeetCode
Can you solve this real interview question? Excel Sheet Column Number - Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27
leetcode.com
2. 문제 설명
- A이 주어지면 1, Z이 주어지면 26을 반환
- AA이 주어지면 27, AB이 주어지면 28 와 같은 규칙으로 수가 주어졌을 때 문자열을 반환
- 즉, 엑셀의 열이름이 주어졌을 때 몇 번째 열인지를 생각하면 되고 A부터 Z까지 26개이니 26진법으로 생각
- 26진법이면 26으로 나눈 나머지가 0부터 25까지 나옴
- 그런데 A~Z까지 0을 나타내는 수가 없다는 것에 유의, 즉 0이 아니라 1이 A가 되고 26이 Z가 되어 1부터 26까지 나와서 하나의 차이가 존재한다.
3. 처음 풀이
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
result = 0
for i in columnTitle:
num = ord(i)-64 #ord('A')=65, ord('Z')=90이다. 64를 빼면 A는 1, Z는 26에 해당
result = 26*result + num #이전 결과를 26배 하면 한 칸 더 높은 자릿수를 나타냄. 즉 ABC에서 A는 1*26²을, B는 2*26, C는 3을 나타냄
return result
4. 다른 풀이
- 26배씩 하면서 더하지 말고 바로 거듭제곱 연산 **을 써도 된다.
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
num = 0
columnTitle = columnTitle[::-1]
for i in range(len(columnTitle)):
num += (ord(columnTitle[i])-64)*pow(26,i)
return num
5. 배운 점
- 문자를 받고 해당하는 유니코드를 반환하는 ord 함수와 유니코드를 받고 해당하는 문자를 반환하는 chr 함수
ord('A') #65
ord('B') #66
chr(65) #'A'
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 191(Number of 1 Bits, Python) (1) | 2023.12.08 |
---|---|
LeetCode 190(Reverse Bits, Python) (1) | 2023.12.07 |
LeetCode 169(Majority Element, Python) (0) | 2023.12.05 |
LeetCode 168(Excel Sheet Column Title, Python) (0) | 2023.12.04 |
LeetCode 160(Intersection of Two Linked Lists, Python) (1) | 2023.12.03 |