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

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

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

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
        
        if (0 == n) {
            return 0;
        }
        
        int res = 0;
        for (int i = 1; i <= n; i++) {
            res += process(i);
        }
        return res;
    }
    
    public int process(int num) {
        String str = num + "";
        int total = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '1') {
                total++;
            }
        }
        return total;
    }
}
全部评论

相关推荐

每晚夜里独自颤抖:要求太多的没必要理
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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