java 求n位水仙花数
我想用数值int转字符串然后字符串转数值,遍历求水仙花数,但代码有问题,求教import java.util.Scanner;
public class shuixianhua {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
System.out.println("请输入n位水仙花数");
int y = x.nextInt();
int yy=(int)Math.pow(10, y);
for (int i = 100; i <= yy; i++) {
String z = String.valueOf(i);
int sum=0;
for (int ii = 0; ii < y; ii++) {
String v= String.valueOf(z.charAt(ii));
int a = Integer.parseInt(v);
sum += Math.pow(a,3);
System.out.println(z.charAt(ii));
}
if(sum==i){
System.out.println(i);
}
}
}
} 顶
本帖最后由 傻眼貓咪 于 2022-1-6 19:16 编辑
你的代码 public class shuixianhua 必须和文件名相同 本帖最后由 傻眼貓咪 于 2022-1-6 19:26 编辑
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
int a, b;
Scanner string = new Scanner(System.in);
System.out.println("请输入 n 位水仙花数:");
int n = string.nextInt();
a = (int)Math.pow(10, n - 1);
b = (int)Math.pow(10, n) - 1;
for (int i = a; i < b; i++) {
int num = Integer.parseInt(String.valueOf(i));
int sum = 0, x;
while(true){
if(num == 0) break;
x = num%10;
num /= 10;
sum += Math.pow(x, n);
}
if(sum == i) System.out.println(sum);
}
}
}请输入n位水仙花数:
3
153
370
371
407
页:
[1]