728x90
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
q = columnNumber
ans = ""
while True:
if q == 0:
break
q, r = divmod(q-1,26)
ans += chr(r + ord('A'))
return ans[::-1]
0-indexing이기 때문에 q-1을 한 값에 divmod를 26으로 추출
대문자를 출력해야 되기 때문에 ord("A") ,즉 65를 기준으로 r(나머지) 를 더한 값을
chr에 인자로 넣어서 character를 ans에 추가해준다.
return은 역순으로 해줘야 한다.
dict을 활용한 방법
alpha = {}
az = [chr(x) for x in range(ord("A"),ord("A")+26)]
for i,a in enumerate(az):
alpha[i] = a
print(alpha)
columnNumber = 2147483647
q = columnNumber
ans = ""
while True:
if q == 0:
break
q, r = divmod(q-1,26)
ans += alpha[r]
print(ans[::-1])
# output
# {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J', 10: 'K', 11: 'L', 12: 'M', 13: 'N', 14: 'O', 15: 'P', 16: 'Q', 17: 'R', 18: 'S', 19: 'T', 20: 'U', 21: 'V', 22: 'W', 23: 'X', 24: 'Y', 25: 'Z'}
# FXSHRXW
728x90
'Leetcode' 카테고리의 다른 글
[LeetCode] Excel Sheet Column Number 파이썬 (ord) (0) | 2021.04.03 |
---|---|
[LeetCode] Majority Element 파이썬 (dict, Counter, median) (0) | 2021.04.02 |
[LeetCode] Two Sum II - Input array is sorted 파이썬 (0) | 2021.04.02 |
[LeetCode] Intersection of Two Linked Lists (switch) (0) | 2021.04.02 |
[LeetCode] Linked List Cycle 파이썬 (is operator, id) (0) | 2021.04.01 |
댓글