51,410
社区成员
发帖
与我相关
我的任务
分享
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i, j, n, m, a, b, c;
while (sc.hasNextInt()) {
m = sc.nextInt();
n = sc.nextInt();
for (i = m, j = 0; i <= n; i++) {
a = i / 100;
b = i / 10 % 10;
c = i % 10;
if (a * a * a + b * b * b + c * c * c == i) {
if (j > 0) {
System.out.print(" " + i);
} else {
System.out.print(i);
}
j++;
}
}
if (j == 0) {
System.out.print("no");
}
System.out.println();
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int start, end;
int[] results = new int[10];
while (sc.hasNext()) {
start = sc.nextInt();
end = sc.nextInt();
int counter = 0;
for (int i = start; i < end + 1; i++) {
if(isSpecial(i)) {
// 将结果先放在数组中,方便控制输出和换行
results[counter] = i;
counter++;
}
}
if(results[0] == 0) {
System.out.println("no");
} else {
for (int i = 0; i < counter; i++) {
if(i == 0) {
System.out.print(results[i]);
} else {
System.out.print(" "+results[i]);
}
/*if(i == counter-1) {
// 最后一个结果换行
System.out.println(results[i]);
} else {
System.out.print(results[i]+" ");
}*/
}
System.out.println();
}
}
}
private static boolean isSpecial(int n) {
int a, b, c;
// 个位
a = n%10;
// 十位
b = (n/10)%10;
// 百位
c = (n/100);
return (a*a*a + b*b*b + c*c*c) == n;
}
}
感谢
如果第一组数据范围内有水仙花数,数组被赋值;但是如果下一组没有水仙花数的话,数组就没有被再覆盖,还是上一组的结果,但是counter为0,导致for循环无法输出,致此时程序无法向下执行。
100
999
153 370 371 407
100
500
153 370 371 407
[/code]
,好像确实是要写成if(counter==0)。修改后杭电OJ测试通过了。
但是我还有点不明白,results数组用来存放水仙花数,但凡找到一个水仙花数肯定是先放在数组的第0个位置,所以如果连第零个位置的值都是0的话(java声明的数组值默认都是0),那就说明该数组没有被覆盖过,就没有水仙花数,所以我才写成if(results[0] == 0),关于这一点还请指教。
对于start和end之间相差10,因为我知道该题的结果(100~999之间的水仙花数只有四个),为了省事儿我就直接写成10,肉眼可见的程序输出是对的但是在OJ上执行不通过。