#java

为什么大家要想的这么复杂呢 虽然我的方法比较low,可能慢 但是我2分钟就写完了呀(#^.^#)

import java.util.*;
public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
        int count = 0;
        // 循环 1->n
        for(int i=1;i<=n;i++){
            count += f(i); 
        }
        return count;
    }
    // 判断有多少个1
    public int f(int n){
        String str = n+"";
        char[] c = str.toCharArray();
        int count = 0;
        for(int i=0;i<c.length;i++){
            if(c[i]=='1'){
                count++;
            }
        }
        return count;
    }
}

简化后

public int NumberOf1Between1AndN_Solution(int n) {
       int count = 0;
        while(n>0){
            String str = String.valueOf(n);
            char [] chars = str.toCharArray();
            for(int i=0;i<chars.length;i++){
                if(chars[i]=='1')
                    count++;
            }
            n--;
        }
        return count;
    }