统计从1到N之间自然数中包含有多少个2?如1-20中,有2,12,20这三个自然数,有3个2

 1  public static void main(String[] args) {
 2         long start = System.currentTimeMillis();
 3         int sum1 = count(20);
 4         long end = System.currentTimeMillis();
 5 
 6 
 7         System.out.println("统计的数量:" + sum1);
 8         System.out.println("时间(毫秒):" + (end - start));
 9     }
10 
11     public static int count(int n) {
12         List<String> list = new ArrayList<>();
13         if (n <= 0) {
14             return 0;
15         }
16         int count = 0;
17         for (int j = 2; j <= n; j++) {
18             String str = j + "";
19             for (int k = 0; k < str.length(); k++) {
20                 if ((str.charAt(k) + "").equals("2")) {
21                     count++;
22                     list.add(str);
23                 }
24             }
25         }26         return count;
27     }

猜你喜欢

转载自www.cnblogs.com/xieshilin/p/12392540.html