将数字转换为 Excel 列 headers
Converting numbers to Excel column headers
这是 LeetCode 上的一道题,被归类为“简单”。我已经为此工作了几个小时,甚至还请来了一位同事。我无法找出我逻辑中的错误。我不是在寻找完全不同的问题解决方案。如果有人能指出我的方法有什么问题,我将不胜感激。
想法是将 int 转换为表示为 Excel 列的字符串 header (1='A', 2='B' ... 27='AA',等等)。这是我的代码,带有注释。该代码适用于许多输入(例如,735 -> 'ABG'),但对其他输入无效(例如,702 -> 'ZZ')。
def numToCol(n):
# Generate a key such that {1:'A', 2:'B', 3:'C'... 26:'Z'} (this works fine)
key = {}
for i in range(65, 91):
key[i-64] = chr(i)
# According to Wikipedia, the number of digits in the bijective base-k
# numeral representing a nonnegative integer n is floor(logk((n+1)*(k-1)))
# exp = num of letters in final string
exp = int(math.log((n+1)*25, 26)) # int() rounds it down
col_name = ''
num = n
# The final number is represented by a(26**0) + b(26**1) + c(26**2) + ...
# If exp = 3, then there are 3 letters in the final string, so we need to find
# a(26**2) + b(26**1) + c(26**0).
# If exp = 3, i iterates over 2, 1, 0.
for i in range(exp-1, -1, -1):
# factor = how many 26**i's there are in num, rounded down
factor = int(num/(26**i))
# add to the string the letter associated with that factor
col_name = col_name + key[factor]
# update the number for next iteration
num = num - (factor*(26**i))
return col_name
这是我编写的一个反向函数(将字符串转换为 int)。这有助于了解预期结果应该是什么。确认有效。
def colToNum(string):
'''
Converts an upper-case string (e.g., 'ABC') to numbers as if they were
column headers in Excel.
'''
key = {}
for i in range(65, 91):
key[chr(i)] = i-64
new = []
for idx, val in enumerate(string[::-1]):
new.append(key[val] * 26**idx)
return sum(new)
你检查过this answer了吗?那个看起来像你所要求的。我也分享如下代码。
def excel_column_number_to_name(column_number):
output = ""
index = column_number-1
while index >= 0:
character = chr((index%26)+ord('A'))
output = output + character
index = index/26 - 1
return output[::-1]
for i in xrange(1, 1024):
print "%4d : %s" % (i, excel_column_number_to_name(i))
找到问题所在,但没有找到优雅的解决方法。您可能已经注意到,每当您到达 Z 并且有多个字母时,代码总是会失败。那是因为应该是2和26的因数,意思是BZ,变成了3和0。这个零导致了问题。这是设法使代码工作的技巧。除了 if-statement(并且 num = num - (factor*(26**i))
已向上移动)
之外,其他一切都一样
for i in range(exp-1, -1, -1):
# factor = how many 26**i's there are in num, rounded down
factor = int(num/(26**i))
num = num - (factor*(26**i))
if num == 0 and i!=0:
factor -=1
num = 26
# add to the string the letter associated with that factor
col_name = col_name + key[factor]
这个 if-statements 只是修复了当结果中有多个字母时发生的这些“Z”情况。
这是 LeetCode 上的一道题,被归类为“简单”。我已经为此工作了几个小时,甚至还请来了一位同事。我无法找出我逻辑中的错误。我不是在寻找完全不同的问题解决方案。如果有人能指出我的方法有什么问题,我将不胜感激。
想法是将 int 转换为表示为 Excel 列的字符串 header (1='A', 2='B' ... 27='AA',等等)。这是我的代码,带有注释。该代码适用于许多输入(例如,735 -> 'ABG'),但对其他输入无效(例如,702 -> 'ZZ')。
def numToCol(n):
# Generate a key such that {1:'A', 2:'B', 3:'C'... 26:'Z'} (this works fine)
key = {}
for i in range(65, 91):
key[i-64] = chr(i)
# According to Wikipedia, the number of digits in the bijective base-k
# numeral representing a nonnegative integer n is floor(logk((n+1)*(k-1)))
# exp = num of letters in final string
exp = int(math.log((n+1)*25, 26)) # int() rounds it down
col_name = ''
num = n
# The final number is represented by a(26**0) + b(26**1) + c(26**2) + ...
# If exp = 3, then there are 3 letters in the final string, so we need to find
# a(26**2) + b(26**1) + c(26**0).
# If exp = 3, i iterates over 2, 1, 0.
for i in range(exp-1, -1, -1):
# factor = how many 26**i's there are in num, rounded down
factor = int(num/(26**i))
# add to the string the letter associated with that factor
col_name = col_name + key[factor]
# update the number for next iteration
num = num - (factor*(26**i))
return col_name
这是我编写的一个反向函数(将字符串转换为 int)。这有助于了解预期结果应该是什么。确认有效。
def colToNum(string):
'''
Converts an upper-case string (e.g., 'ABC') to numbers as if they were
column headers in Excel.
'''
key = {}
for i in range(65, 91):
key[chr(i)] = i-64
new = []
for idx, val in enumerate(string[::-1]):
new.append(key[val] * 26**idx)
return sum(new)
你检查过this answer了吗?那个看起来像你所要求的。我也分享如下代码。
def excel_column_number_to_name(column_number):
output = ""
index = column_number-1
while index >= 0:
character = chr((index%26)+ord('A'))
output = output + character
index = index/26 - 1
return output[::-1]
for i in xrange(1, 1024):
print "%4d : %s" % (i, excel_column_number_to_name(i))
找到问题所在,但没有找到优雅的解决方法。您可能已经注意到,每当您到达 Z 并且有多个字母时,代码总是会失败。那是因为应该是2和26的因数,意思是BZ,变成了3和0。这个零导致了问题。这是设法使代码工作的技巧。除了 if-statement(并且 num = num - (factor*(26**i))
已向上移动)
for i in range(exp-1, -1, -1):
# factor = how many 26**i's there are in num, rounded down
factor = int(num/(26**i))
num = num - (factor*(26**i))
if num == 0 and i!=0:
factor -=1
num = 26
# add to the string the letter associated with that factor
col_name = col_name + key[factor]
这个 if-statements 只是修复了当结果中有多个字母时发生的这些“Z”情况。