172. 阶乘后的零
给定一个整数 n,返回 n! 结果尾数中零的数量。
示例 1:
输入: 3 输出: 0 解释: 3! = 6, 尾数中没有零。
示例 2:
输入: 5 输出: 1 解释: 5! = 120, 尾数中有 1 个零.
说明: 你算法的时间复杂度应为 O(log n) 。
代码:
class Solution:
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
#### the first method, 超时了
# sum = 1
# count = 0
# while n != 0:
# sum *= n
# n -= 1
# strs = str(sum)
# for i in range(len(strs)-1, -1, -1):
# if strs[i] == '0':
# count += 1
# continue
# else:
# break
# return count
#### the second method
"""
于是想到求0也就是求其中2*5的个数,也就是5的个数,因为每一个偶数都含2,
只要有5肯定有2。然后我就遍历求能不能被5整除了。
"""
count = 0
while n > 0:
n = n // 5
count += n
return count
171. Excel表列序号
给定一个Excel表格中的列名称,返回其相应的列序号。
例如,
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ...
示例 1:
输入: "A" 输出: 1
示例 2:
输入: "AB" 输出: 28
示例 3:
输入: "ZY" 输出: 701
代码:
class Solution3:
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
"""
字符与ASCII码的转换:
- 字符转ASCII码 ord(str),如ord(‘A’)为65
- ASCII码转字符 chr(int),如chr(65)为’A’
"""
#### the first method
# res = 0
# for str in s:
# res = res * 26 + ord(str) - ord('A') + 1
# print(res)
# return res
#### the second method
# res = 0
# for i in range(len(s)-1, -1, -1):
# res += (ord(s[i]) - 64) * 26**(len(s) - i - 1)
# return res
#### the third method
result = 0
for i in s:
result = result * 26
x = ord(i) - 64
result += x
return result
168. Excel表列名称
给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ...
示例 1:
输入: 1 输出: "A"
示例 2:
输入: 28 输出: "AB"
示例 3:
输入: 701 输出: "ZY"
代码:
class Solution:
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
res = ""
while n != 0:
res = chr((n-1) % 26 + 65) + res
n = (n -1) // 26
return res