程序分析:
要统计1到100之间出现了几次数字9,可以采用三种不同的方法来实现。以下是三种不同方法的解题思路、代码示例以及各自的优缺点:
方法1: 遍历法
思路:
public class CountNinesMethod1 {
public static void main(String[] args) {
int count = 0;
for (int i = 1; i <= 100; i++) {
int num = i;
while (num > 0) {
if (num % 10 == 9) {
count++;
}
num /= 10;
}
}
System.out.println("数字9出现的次数: " + count);
}
}
优点:
缺点:
方法2: 字符串法
思路:
charAt
方法来检查每个字符是否是数字9。public class CountNinesMethod2 {
public static void main(String[] args) {
int count = 0;
for (int i = 1; i <= 100; i++) {
String numStr = String.valueOf(i);
for (int j = 0; j < numStr.length(); j++) {
if (numStr.charAt(j) == '9') {
count++;
}
}
}
System.out.println("数字9出现的次数: " + count);
}
}
优点:
缺点:
方法3: 数学法
思路:
public class CountNinesInRange {
public static int countNinesInRange(int n) {
int count = 0;
int multiplier = 1;
int remainder = 0;
while (n > 0) {
int currentDigit = n % 10;
n /= 10;
count += n * multiplier;
if (currentDigit > 9) {
count += multiplier;
} else if (currentDigit == 9) {
count += remainder + 1;
}
remainder = currentDigit * multiplier + remainder;
multiplier *= 10;
}
return count;
}
public static void main(String[] args) {
int n = 100;
int result = countNinesInRange(n);
System.out.println("在1到" + n + "之间,数字9出现的总次数为: " + result);
}
}
优点:
缺点:
总结:
在这种情况下,方法3(数学法)通常是最好的选择。它效率较高,不需要遍历所有数字,而是利用数学规律直接计算结果。方法1和方法2适用于小范围的数字,但在大范围的情况下可能效率较低。然而,对于更复杂的数字统计问题,方法1和方法2可能更易理解和实现。因此,最佳方法取决于具体问题的要求和数据规模。