题解 |从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;
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 12:23
转人工😡
门口唉提是地铁杀:五次握手了
点赞 评论 收藏
分享
06-04 09:27
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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