题目:打印出所有的 "水仙花数 ",所谓 "水仙花数 "是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个 "水仙花数 ",因为153=1的三次方+5的三次方+3的三次方。
我想通过String数组将其实现,但是运行没有结,请高手指教
public class Sushu {
public static void main(String args[]) {
for(int i = 100; i<=999 ;i++) {
String m = Integer.toString(i);
int n = (int)m.charAt(0);
int h = (int)m.charAt(1);
int j = (int)m.charAt(2);
if(i == n*n*n + h*h*h +j*j*j) {
System.out.print(" " + i);
}
}
}}
我想通过String数组将其实现,但是运行没有结,请高手指教
public class Sushu {
public static void main(String args[]) {
for(int i = 100; i<=999 ;i++) {
String m = Integer.toString(i);
int n = (int)m.charAt(0);
int h = (int)m.charAt(1);
int j = (int)m.charAt(2);
if(i == n*n*n + h*h*h +j*j*j) {
System.out.print(" " + i);
}
}
}}
for(int i = 100; i < 1000; i ++) {
if(isNumber(i)) {
System.out.println(i);
}
}
}
public static boolean isNumber(int num) {
int q = num / 100;
int b = (num % 100) / 10;
int g = num % 10;
if((Math.pow(q, 3) + Math.pow(b, 3) + Math.pow(g, 3)) == (double)num) {
return true;
}
return false;
}
}这个我已经测试好了, 你试试。
String m = Integer.toString(i);
int n = Integer.parseInt(m.charAt(0)+"");
int h = Integer.parseInt(m.charAt(1)+"");
int j = Integer.parseInt(m.charAt(2)+"");
if(i == n*n*n + h*h*h +j*j*j) {
System.out.print(" " + i);
}
}
public static void main(String[] args) {
int first;//个位
int second;//十位
int three;//百位
for(int i=100;i<1000;i++){
three=i/100;
second=(i-three*100)/10;
first=i-second*10-three*100;
if(i==first*first*first+second*second*second+three*three*three){
System.out.println(i);
}
} }}
可改为 int n = m.charAt(0)-'0';
int h = m.charAt(1)-'0';
int j = m.charAt(2)-'0';
减去'0'字符后就是字符和0之间的位移,恰好就是数字值
大概比直接计算要快一点,代码有点多,还有说明,所以放在部落格里了:
http://blog.csdn.net/clariones/archive/2010/10/11/5933035.aspx希望能有帮助