水仙花数:ABC=A^3+B^3+C^3(三位数)
public class test {
public static void main(String[] args) {
double sum = 0;
for(int n = 100;n < 1000;n ++){
String number = Integer.toString(n);
int[] a = new int[number.length()];
for(int i = 0;i < number.length();i ++){
a[i] = Integer.parseInt(number.charAt(i) + "");
}
for(int i = 0;i < a.length;i ++){
sum += Math.pow(a[i],3);
}
if(sum == n){
System.out.println(n);
}
sum = 0;
}
}
}
结果是:153 370 371 407
代码本身朴实无华,主要是截取三个位数那里动了下小心思,传统方法就是通过除和取余来截取整数的位数。另外强行将字符变成串的方法就是加一个空串(并不是空格串),上面也有所体现。