剑指 Offer 43. 1~n 整数中 1 出现的次数

题目描述:

输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。

例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。

 

限制:

  • 1 <= n < 2^31

 

 

 

 

 

复制代码
class Solution{
    public int countDigitOne(int n){
        int digit=1,res=0;
        int high=n/10,low=0,cur=n%10;
        while(high!=0||cur!=0){
            if(cur==0) res+=high*digit;
            else if(cur==1) res+=high*digit+low+1;
            else res+=(high+1)*digit;
            low+=cur*digit;
            cur=high%10;
            high/=10;
            digit*=10;
        }
        return res;
    }
}
复制代码

 

posted @   ZDREAMER  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!
点击右上角即可分享
微信分享提示