原谅我用一个非常简单粗暴的方法解决此题!思路:从 1 开始遍历这个 n,把每个数都转化并且存到一个字符串里;然后把最终得到的这个字符串转换成字符数组,定义一个 count 用来记录符合 1 的次数;最后遍历这个字符数组,如果遍历到的字符是'1',count累计,最后输出count即可。

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
        if(n <= 0){
            return 0;
        }
        String str = "";
        for(int i = 1; i <= n; i++ ){
            str = str + String.valueOf(i);
        }
        char ss[] = str.toCharArray();
        int count = 0;
        for(int i = 0; i < ss.length; i++){
            if(ss[i] == '1'){
                count++;
            }
        }
        return count;
    }
}