题目要求:
请编写一个方法,输出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);
}
}