1、题目描述:
Problem Description
春天是鲜花的季节,水仙花就是其中最迷人的代表,数学上有个水仙花数,他是这样定义的:
“水仙花数”是指一个三位数,它的各位数字的立方和等于其本身,比如:153=1^3+5^3+3^3。
现在要求输出所有在m和n范围内的水仙花数。
Input
输入数据有多组,每组占一行,包括两个整数m和n(100<=m<=n<=999)。
Output
对于每个测试实例,要求输出所有在给定范围内的水仙花数,就是说,输出的水仙花数必须大于等于m,并且小于等于n,如果有多个,则要求从小到大排列在一行内输出,之间用一个空格隔开;
如果给定的范围内不存在水仙花数,则输出no;
每个测试实例的输出占一行。
Sample Input
100 120
300 380
Sample Output
no
370 371
2、分析:
对于格式处理的思路:
我采用的方法是将水仙花数保存到ArrayList中,然后在最后输出的时候,遍历ArrayList。
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Main problem = new Main();
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int m = in.nextInt();
int n = in.nextInt();
int count = 0;
List<Integer> out = new ArrayList<>();
for (int i = m; i <= n; i++) {
int a = i / 100;
int c = i % 100;
int b = c / 10;
c = c % 10;
if (i == a * a * a + b * b * b + c * c * c){
count ++;
out.add(i);
}
}
if(count == 0){
System.out.println("no");
}else{
for (int i = 0; i < count; i++) {
System.out.print(out.get(i));
if(i < count - 1){
System.out.print(" ");
}
}
System.out.println();
}
}
}
}
别人的处理思路:采用字符串来实现
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Main problem = new Main();
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int m = in.nextInt();
int n = in.nextInt();
String s = "";
for (int i = m; i <= n; i++) {
int a = i / 100;
int c = i % 100;
int b = c / 10;
c = c % 10;
if (i == a * a * a + b * b * b + c * c * c){
s += i + " ";
}
}
s = s.trim();
if(s.length() == 0){
System.out.println("no");
}else{
System.out.println(s);
}
}
}
}
感觉使用String来处理输出格式还是很方便的。