整数中1出现的次数

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

https://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6?tpId=13&tqId=11184&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&tab=answerKey

public int NumberOf1Between1AndN_Solution(int n) {

        int base = 1;
        int res = 0;
        while(base <= n){
            int b = n%base;
            int a = n/base;
            int cur = a%10;
            a = a/10;
            if(cur > 1)
                res += (a+1)*base;
            else if(cur == 0)
                res += a*base;
            else res += a*base+b+1;
            base *= 10;
        }
        return res;
    }

剑指offer 文章被收录于专栏

为刷过的每一道题都书写一篇题解,便于重复练习~

全部评论

相关推荐

点赞 评论 收藏
分享
2 收藏 评论
分享
牛客网
牛客企业服务