请编写一个方法,输出0到(包括n)中数字2出现了几次。 给定个正整教n, 请返回0到的数字中2出现了几次。

题目要求:
请编写一个方法,输出0到(包括n)中数字2出现了几次。
给定个正整教n, 请返回0到的数字中2出现了几次。

代码展示:

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);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43815275/article/details/113619775