我想计算在一个数字范围内有多少数字的数字4
例如1-100计算所有具有数字编号的数字
即4,14,24,34,40,41,42,43,44,45,46,47,48,49,54,64,74,84和94总共19个数字
我在计算数字4的整数时遇到问题请帮助!!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int count = 0;
while (true) {
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt();
if (num1 != 0 || num2 != 0) {
for (int num = num1; num <= num2; num++) {
while (num != 0) {
int i = num % 10;
if (i == 4) {
count++;
break;
}
num = num / 10;
}
}
System.out.println(count);
}
else
break;
}
}
}
答案 0 :(得分:1)
要检查某个数字是否包含特定数字,可以使用以下技巧:
String::contains
(简单)以下是您可以使用的一段代码如果您使用的是Java 8:
int number = 4, min = 0, max = 100;
String numberToString = String.valueOf(number);
long count = IntStream.rangeClosed(min, max) //Range of numbers between min and max
.filter(n -> String.valueOf(n).contains(numberToString)) // Use the filter
.count();// Then count the result
System.out.println(count); // 19
答案 1 :(得分:0)
//您的代码需要进行一些更改..这是解决方案......
public class MaxOccurance {
public static void main(String[] args) {
int count = 0;
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt(), temp;
if (num1 != 0 || num2 != 0) {
for (int num = num1; num <= num2; num++) {
temp = num;
while (temp != 0) {
int i = temp % 10;
if (i == 4) {
count++;
// break;
}
temp = temp / 10;
}
}
System.out.println(count);
}
}
}