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

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

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

描述
输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数
例如,1~13中包含1的数字有1、10、11、12、13因此共出现6次

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
        int num = 0;
        for(int i = 1; i <= n; i++){
            String strNum = Integer.toString(i);
            for(int j = 0; j < strNum.length(); j++){
                if(strNum.charAt(j) == '1'){
                    num += 1;
                }
            }
        }
        return num;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客企业服务