求1到N之间数字1一共出现了多少次?
在抖音上刷到一个问题:求1到N之间数字1一共出现了多少次?
解决:先获取用户输入的数据,将数据从1到n遍历,再将每一个数字转换成字符串,判断字符串中是否含有"1",如果没有立即进行下一轮循环。如果有将字符串转换为char类型的数组,再遍历数组中的数据是不是’1’,如果是则计数加一。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入N:");
int n = sc.nextInt();
int count = 0;
for(int i = 1;i <= n;i++){
String str = String.valueOf(i);
//当字符串中不包含1时,进入下一轮循环
if(!str.contains("1")){
continue;
}
for (int j = 0;j < str.length();j++){
char[] chars = str.toCharArray();
if(chars[j] == '1'){
count++;
}
}
}
System.out.println("从1到"+n+"一共出现了"+count+"次'1'");
}