题解 |从1到n整数中1出现的次数#

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

https://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n) {
        long base=1;
        long res=0;
        while(base<=n){
            long cur=(n/base)%10;
            long low=n%base;
            long high=n/base/10;

            if (cur>1) {
                res+=(high+1)*base;
            }else if(cur==1){
                res+=(high*base)+(1+low);
            }else {
                res+=high*base;
            }
            base=base*10;
        }
        return (int)res;
    }
};

全部评论

相关推荐

06-25 09:33
厦门大学 Java
程序员饺子:现在日常估计没啥hc了,等到八月多估计就慢慢有了。双九✌🏻不用焦虑的
投递快手等公司7个岗位
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 12:10
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务