我正在努力研究ArmStrong号码, 所以这是我的代码
public class NewArmStrongNumber {
public static void main(String[] args) {
int num = 153,armNum=0;
while(num>0){
int temp = num%10;
armNum = armNum+(temp*temp*temp);
num = num/10;
}
System.out.println(num==armNum);
}
}
我得到的结果是假的,我知道为什么吗?
答案 0 :(得分:0)
num每次减少,因为它是/ 10,当num为0时循环退出。
每次循环时,armNum都有可能增加。
因此,除非armNum为0,否则它将为false。
答案 1 :(得分:0)
您必须将num
保存在其他变量中,以便将其与armNum
进行比较。这是因为num
在while
循环结束时总是 0 。因此(num==armNum)
始终为false
答案 2 :(得分:0)
根据Armstrong numbers的定义:
package math.numbers;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Created by Michael
* Creation date 7/28/2017.
* @link https://stackoverflow.com/questions/45378317/confused-with-int-assignments-in-java
* @link http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/arms.html
*/
public class Armstrong {
public static void main(String[] args) {
List<Integer> armstrong = IntStream.range(0, 1000000).filter(Armstrong::isArmstrong).boxed().collect(Collectors.toList());
System.out.println(armstrong);
}
public static boolean isArmstrong(int n) {
boolean armstrong = false;
int sum = 0;
int temp = n;
while (temp > 0) {
int x = temp % 10;
sum += x * x * x;
temp /= 10;
}
armstrong = (sum == n);
return armstrong;
}
}
这是我得到的输出:
[0, 1, 153, 370, 371, 407]