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

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

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

//方法一:
//遍历每一个数,将每个数转换成字符串,判断字符串中含有'1'字符的个数;
class Solution {
public:
    int Count(string s){//写一个计算字符串中'1'的个数
        int num=0;
        for(auto &e:s){
            if(e=='1')
                num++;
        }
        return num;
    }
    int NumberOf1Between1AndN_Solution(int n) {
        int ret=0;
        for(int i=1;i<=n;i++){
            ret+=Count(to_string(i));//将整数转换成字符串的函数
        }
        return ret;

 //方法二:       
 //遍历每个数,将每个数/10判断个位为1,在循环%10直到数为0;      
        /*
        if(n<=0) return 0;
    int ret=0;
    for(int i=1;i<=n;i++){//遍历每个数
        int temp=i;
        while(temp){//循环拆分判断个位是否有1,直到数为0;
            if(temp%10==1)
                ret++;
            temp/=10;
        }
    }
        return ret;
        */
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
2024-12-29 15:37
已编辑
西华大学 图像识别
程序员牛肉:去不了,大厂算法卡学历吧
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务