剑指offer整数中1出现的次数(从1到n整数中1出现的次数)

题目描述

求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。

思路

     求1~n整数中1出现的次数(《剑指offer》面试题43) - Excaliburer - 博客园  这篇博客写的很好

     当前位为x

  1. 如果x>1:(高位数字+1)*10^(i-1)
  2. 如果x==1:高位数字*10^(i-1)+(低位数字+1)
  3. 如果x<1:高位数字*10^(i-1)
  4. 高位数字=n / 10^i
  5. 当前位:temp=n / 10^(i-1)   cur=temp%10
  6. 低位数字=n - temp*10^(i-1)
# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1Between1AndN_Solution(self, n):
        # write code here
        if n<1:
            return 0
        high=n
        i=1
        res=0
        while high>0:
            high=n/10**i
            temp=n/10**(i-1)
            cur=temp%10
            low=n-temp*10**(i-1)
            if cur>1:
                res+=(high+1)*10**(i-1)
            elif cur<1:
                res+=high*10**(i-1)
            else:
                res+=high*10**(i-1)+(low+1)
            i+=1
        return res

转化成字符求解

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1Between1AndN_Solution(self, n):
        # write code here
        count = 0
        for i in range(1,n+1):
            ss = str(i)
            for j in range(len(ss)):
                if ss[j]=='1':
                    count+=1
        return count

测试用例

if __name__=='__main__':
    s=Solution()
    n=2019
    print(s.NumberOf1Between1AndN_Solution(n))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值