美文网首页
43-整数中1出现的次数

43-整数中1出现的次数

作者: 一方乌鸦 | 来源:发表于2020-05-06 09:15 被阅读0次

输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。

例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。

直接找规律的话,正常面试中很难做到

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
        int count = 0;
        for (int i = 1; i <= n; i++) {
            count += count(String.valueOf(i));
        }
        return count;
    }
    private int count(String s) {
        int c = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '1') c++;
        }
        return c;
    }
}

相关文章

网友评论

      本文标题:43-整数中1出现的次数

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