Excel Sheet
168. Excel Sheet Column Title
思路: 數字 轉 字母. reference map 0 ~ 25 對應到 A - Z 所以在處理n 的時候要 做 (n - 1) // 26.
26 => (26 - 1) % 26 = 25, ref[25] = 'Z'
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
dic = {}
res = []
for i in range(65, 91):
dic[i - 65] = str(unichr(i))
while n:
res.insert(0, dic[(n-1) % 26])
n = (n-1) // 26
return "".join(res)
171. Excel Sheet Column Number
思路: 字母 轉 數字. 做26進位加法
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
ref = {}
res = 0
for i in range(26):
ref[str(unichr(i + 65))] = i + 1
s = list(s)
multi = 0
for i in range(len(s)-1, -1, -1):
res += ref[s[i]] * 26 ** multi
multi += 1
return res
思路: 數字 轉 字母. reference map 0 ~ 25 對應到 A - Z 所以在處理n 的時候要 做 (n - 1) // 26.
26 => (26 - 1) % 26 = 25, ref[25] = 'Z'
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
dic = {}
res = []
for i in range(65, 91):
dic[i - 65] = str(unichr(i))
while n:
res.insert(0, dic[(n-1) % 26])
n = (n-1) // 26
return "".join(res)
171. Excel Sheet Column Number
思路: 字母 轉 數字. 做26進位加法
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
ref = {}
res = 0
for i in range(26):
ref[str(unichr(i + 65))] = i + 1
s = list(s)
multi = 0
for i in range(len(s)-1, -1, -1):
res += ref[s[i]] * 26 ** multi
multi += 1
return res
留言
張貼留言