LeetCode168

LeetCode168:168. Excel表列名称 - 力扣(LeetCode) (leetcode-cn.com)

看了题解,计算除以26的商和余数,利用ASCII码从最后一位依次往前计算。

目前还有一点不明白,第5行。

1 class Solution:
2     def convertToTitle(self, n: int) -> str:
3         res = ''
4         while n:
5             n -= 1
6             n ,y = divmod(n, 26)
7             res = chr(y + 65) + res
8         return res

 

涉及到的语法点:

1. divmod(a, b),函数把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)。

1 >>>divmod(7, 2)
2 (3, 1)
3 >>> divmod(8, 2)
4 (4, 0)
5 >>> divmod(1+2j,1+0.5j)
6 ((1+0j), 1.5j)

2. chr(),用一个整数作参数,返回值是当前整数对应的 ASCII 字符

A:65

B:66

a:97

posted @ 2021-02-24 21:10  vv_869  阅读(212)  评论(0编辑  收藏  举报