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

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

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

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n) {
        int res = 0;
        int cur = 0;
        for(int i = 1; i <= n; ++i)
        {
            cur = i;
            while (cur>10) {// 处理 >10 情况
                if(cur%10 == 1){// 求余运算求1情况,由于十进制所以对10求余
                    res++;
                }
                cur /= 10;// 更新数值
            }
            if(cur%10 == 1 || cur % 10 == 0)// 处理一些特殊情况
            {
                res++;
            }
            //std::cout << " i res : " << i << " " << res << std::endl;
        }
        return res;
    }
};

挤挤刷刷! 文章被收录于专栏

记录coding过程

全部评论

相关推荐

05-12 14:48
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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