寒假每日一题打卡day33—— AcWing 441. 数字统计

【题目描述】

【思路】 枚举 分离数字

import java.io.*;
class Main{
          
   
    public static void main(String args[])throws Exception{
          
   
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String s[] = bf.readLine().split(" ");
        int a = Integer.parseInt(s[0]), b = Integer.parseInt(s[1]);
        int ans = 0;
        for(int i = a; i <= b; i++){
          
   
            String t = String.valueOf(i);
            for(int k = 0; k < t.length(); k++)
                if( t.charAt(k) == 2) ans++;
        }
        System.out.println(ans);
        
    }
}

或使用字符串

import java.io.*;
class Main{
          
   
    public static void main(String args[])throws Exception{
          
   
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String s[] = bf.readLine().split(" ");
        int a = Integer.parseInt(s[0]), b = Integer.parseInt(s[1]);
        int ans = 0;
        for(int i = a; i <= b; i++){
          
   
            String t = String.valueOf(i);
            for(int k = 0; k < t.length(); k++)
                if( t.charAt(k) == 2) ans++;
        }
        System.out.println(ans);
        
    }
}
经验分享 程序员 微信小程序 职场和发展