例如, 1~13 中包含 1 的数字有 1 、 10 、 11 、 12 、 13 因此共出现 6 次
注意:11 这种情况算两次
数据范围:
进阶:空间复杂度 ,时间复杂度
# -*- coding:utf-8 -*- class Solution: def NumberOf1Between1AndN_Solution(self, n): # write code here base = 1 res = 0 while (base <=n): cur = n/base%10 a = n/base/10 b = n%base if(cur ==1): res = res+(a)*base + b +1 elif(cur == 0): res = res +a*base else: res = res +(a+1)*base base =10*base return res 采用了题解方法的python版
class Solution: def NumberOf1Between1AndN_Solution(self, n): # write code here s=str(n) count=0 for i in range(len(s)): a=10**i high=int(n/(10*a)) low=n%a cur=int(n/a)%10 if cur==0: count+=high*a elif cur==1: count+=high*a+(low+1) else: count+=(high+1)*a return count
# -*- coding:utf-8 -*- import collections class Solution: def NumberOf1Between1AndN_Solution(self, n): # write code here sum = 0 numLib = {} N = 1 for num in range(n+1): numLib.setdefault(num,0) numLib[num]=(numLib[num % N]+int(num//N==1)) sum+=numLib[num] if num==10*N-1: N*=10 return sum常规解法:
class Solution: # 常规解法 def NumberOf1Between1AndN_Solution(self, n): sum = 0 for i in range(n+1): while i//10>0: if i%10==1: sum+=1 i=i//10 sum+=int(i%10==1) return sum
思路来自B站视频。以下是原链接
https://www.bilibili.com/video/BV1uJ411573j?t=1824
假设n = 7543 [x] 29
如果要让百位的x = 1,那么需要考虑以下几种情况:
class Solution: def NumberOf1Between1AndN_Solution(self, n): # 运行时间:31ms 占用内存:5860k m = len(str(n)) # 数字的长度 count = 0 for i in range(1, m+1): high = n // 10 ** i # 找到当前位之前的位数 mid = n % 10 ** i // 10 ** (i - 1) # 找当前位 low = n % 10 ** (i - 1) # 找当前位后面的位数 # 第(1)个情况 count += high * (10 ** (i - 1)) if mid > 1: # 第(2.1)个情况 count += 10 ** (i - 1) elif mid == 1: # 第(2.2)个情况 count += (low + 1) return count
# -*- coding:utf-8 -*- class Solution: def NumberOf1Between1AndN_Solution(self, n): # write code here i=0 sum_num=0 highNum=1 # 初始化 while highNum!=0: lowNum=n%(10**i) midNum=n//(10**i)%10 highNum=n//(10**(i+1)) if midNum == 1: sum_num+=(highNum+1)*(lowNum+1)+highNum*(10**i-lowNum-1) if midNum >1: sum_num+=(highNum+1)*(10**i) if midNum <1: sum_num+=highNum*(10**i) i+=1 return sum_num