Please write a method that outputs 0 to (including n) where the number 2 appears several times. Given a positive integer n, please return the number from 0 to 2 for a few times.

Question requirements:
Please write a method, output 0 to (including n) in the number 2 appears several times.
Given a positive integer n, please return the number from 0 to 2 for a few times.

Code display:

public class Main {
    
    
    public static void main(String args[]){
    
    
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int sum=0;
        for(int i=0;i<=n;++i){
    
    
            String s=String.valueOf(i);
            for(int j=0;j<s.length();++j){
    
    
                if(s.charAt(j)=='2')
                    sum++;
            }
        }
        System.out.println(sum);
    }
}

Guess you like

Origin blog.csdn.net/weixin_43815275/article/details/113619775