题解 | #数字中1的个数#

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

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

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
        int base = 1 ;
        int h = n ;
        int l = 0 ;
        int cur = 0 ;
        int res = 0 ;
        while(h > 0) {
            h = n/base/10 ;
            l = n%base ;
            cur = n/base%10 ;
            if(cur == 0) {
                res += h * base ;//借位
            } else if(cur == 1) {
                res += 1 * (l+1) ;//不借位
                res += h * base ;//借位
            } else {
                res += 1* base ;//不借位
                res += h * base ;//借位
            }
            base *= 10 ;
        }
        return res ;
    }
}

一个菜鸟的算法刷题记录 文章被收录于专栏

分享一个菜鸟的成长记录

全部评论

相关推荐

点赞 评论 收藏
分享
05-09 13:22
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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