美文网首页
2021-07-23 整数当中出现1的次数

2021-07-23 整数当中出现1的次数

作者: hlchengzi | 来源:发表于2021-07-23 01:20 被阅读0次

将数字放在一个sring里面,循环遍历判断里面1就好了

 String temp = "";
        int result = 0;
        for(int i = 1;i<n+1;i++){
            temp = String.valueOf(i);
            for(int j = 0;j<temp.length();j++){
                if(temp.charAt(j) == '1'){
                    result++;
                }
            }
        }
        return result;

找规律

int cnt = 0;
        for (int m = 1; m <= n; m *= 10) {
            int a = n / m, b = n % m;
            cnt += (a/10+(a%10>1?1:0)) * m + (a % 10 == 1 ? b + 1 : 0);
        }
        return cnt;

相关文章

网友评论

      本文标题:2021-07-23 整数当中出现1的次数

      本文链接:https://www.haomeiwen.com/subject/xnkumltx.html