JZ43 整数中1出现的次数(从1到n整数中1出现的次数)

题目来源: 整数中1出现的次数(从1到n整数中1出现的次数)_牛客题霸_牛客网

描述

输入一个整数 n ,求 1~n 这 n 个整数的十进制表示中 1 出现的次数
例如, 1~13 中包含 1 的数字有 1 、 10 、 11 、 12 、 13 因此共出现 6 次

注意:11 这种情况算两次

数据范围:1≤n≤30000

进阶:空间复杂度 O(1) ,时间复杂度 O(lognn)

示例1

输入:13

复制返回值:6

我的代码:

找到了一个很清晰的解析,答案解析:力扣

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n) {
        int digit=1,re=0;
        int x=n;
        int low=0,high=0;
        int cur=x%10;
        while(x/10>0 || cur>0){
            cout<<x/10<<"    "<<cur<<endl;
            high = n/(digit*10);
            low = n%digit;
            cout<<high<<"    "<<low<<"    "<<cur<<endl;
            if(cur==0){ //如果当前为为0
                re+=high*digit;
                cout<<"re0:"<<re<<endl;
            }else if(cur==1){//如果当前为为1
                re+=high*digit+low+1;
                cout<<"re1:"<<re<<endl;
            }else if(cur>=2){//如果当前为为2
                re+=(high+1)*digit;
                cout<<"re2:"<<re<<endl;
            }
            x=x/10;
            cur = x%10;
            digit*=10;
        }
        return re;
    }
};

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值