题解 | #整数中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;
        */
    }
};
全部评论

相关推荐

10-30 19:23
已编辑
山东大学(威海) C++
牛至超人:其实简历是不需要事无巨细的写的,让对方知道你有这段经历就行了,最重要的是面试的时候讲细讲明白
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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