21xrx.com
2025-03-27 15:40:37 Thursday
文章检索 我的文章 写文章
“水仙花数”的Java代码
2023-06-15 20:44:36 深夜i     9     0

水仙花数,是指一个三位数,它的各位数字的立方和等于该数本身。例如,153是一个水仙花数,因为1^3 + 5^3 + 3^3 = 153。

下面是用Java语言编写的水仙花数代码:

public class NarcissisticNumber {
  public static void main(String[] args) {
    for (int i = 100; i < 1000; i++) {
      int a = i / 100; //百位
      int b = (i / 10) % 10; //十位
      int c = i % 10; //个位
      if (a * a * a + b * b * b + c * c * c == i) {
        System.out.println(i);
      }
    }
  }
}

代码中,我们用for循环遍历100至999之间的三位数;然后,我们用除法和取余运算,分别得到该数的百位、十位和个位数字;最后,我们判断该数是否满足“各位数字的立方和等于该数本身”,如果满足,则该数是一个水仙花数,我们就将其输出。

关键词:

1. 水仙花数   2. Java代码   3. for循环

  
  

评论区