第2章 面试需要的基础知识
第3章 高质量的代码
第4章 解决面试题的思路
第5章 优化时间和空间效率
面试题39 : 数组中出现次数超过一半的数字
面试题40 : 最小的k个数
面试题42 : 连续子数组的最大和
面试题43 : 从1到n整数中1出现的次数
第6章 面试中的各项能力
第7章 两个面试案例
题目描述
牛客网
求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
解题思路
方法一:
最简单的方法是将数字转为字符串,然后判断每一位是否为‘1’。当然也可以对10求余,判断余数是否为1。这两种方法本质都一样。
实战
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
counts = 0
for i in range(1, n+1):
for s in str(i):
if s == '1':
counts += 1
return counts
方法二:
参考博客
考虑将n的十进制的每一位单独拿出讨论,每一位的值记为weight。
- 个位
从1到n,每增加1,weight就会加1,当weight加到9时,再加1又会回到0重新开始。那么weight从0-9的这种周期会出现多少次呢?这取决于n的高位是多少,看图:
以534为例,在从1增长到n的过程中,534的个位从0-9变化了53次,记为round。每一轮变化中,1在个位出现一次,所以一共出现了53次。
再来看weight的值。weight为4,大于0,说明第54轮变化是从0-4,1又出现了1次。我们记1出现的次数为count,所以:
counts = round + 1 = 54
如果此时weight为0(n=530),说明第54轮到0就停止了,那么:
counts = round = 53 - 十位
对于10位来说,其0-9周期的出现次数与个位的统计方式是相同的,见图:
不同点在于:从1到n,个位每增加10,十位的weight才会增加1,所以,十位的一轮0-9周期内,1会出现10次,即十位为1,然后个位在此基础上增加10,所以就是10次。
再来看weight的值。当此时weight为3,大于1,说明第6轮出现了10次1,则:
count = round*10+10 = 5*10+10 = 60
如果此时weight的值等于0(n=504),说明第6轮到0就停止了,所以:
count = round*10= 5*10 = 50
如果此时weight的值等于1(n=514),那么第6轮中1出现了多少次呢?很明显,这与个位数的值有关,个位数为k,第6轮中1就出现了k+1次(0-k)。我们记个位数为former,则:
count = round*10+former +1= 5*10+4+1 = 55 - 其余位
其余位的计算和十位的计算一致 - 总结
将n的各个位分为两类:个位与其它位。
对个位来说:
(1)若个位大于或等于1,1出现的次数为round*1+1
(2)若个位小于1,1出现的次数为round*1
(3)对其它位来说,记每一位的权值为base,位值为weight,该位之前的数是former,举例如图:
则:
(1)若weight小于1,则1出现次数为round*base
(2)若weight等于1,则1出现次数为round*base+former+1
(3)若weight大于1,则1出现次数为rount*base+base
实战
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
counts = 0
times = len(str(n))
for i in range(times):
if i == 0:
weight = n % 10
rounds = n // 10
if weight >= 1:
counts += (rounds + 1)
else:
counts += rounds
else:
weight = rounds % 10
former = n % 10 ** i
rounds = rounds // 10
if weight > 1:
counts += (rounds + 1) * 10 ** i
elif weight == 1:
counts += rounds * 10 ** i + former + 1
else:
counts += rounds * 10 ** i
return counts
仔细分析,可以发现个位和其他位的计算实际上是一致的。个位中等于1和大于1的情况可以分开计算,然后会发现等于1时也可以用round*base+former+1计算次数。
简化版:
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
counts = 0
times = len(str(n))
rounds = n
for i in range(times):
weight = rounds % 10
former = n % 10 ** i
rounds = rounds // 10
if weight > 1:
counts += (rounds + 1) * 10 ** i
elif weight == 1:
counts += rounds * 10 ** i + former + 1
else:
counts += rounds * 10 ** i
return counts