# Java 计算阿姆斯特朗数

**URL:** <https://www.isharkfly.com/t/java/15114>\
**Category:** 算法\
**Tags:** java, algorithm\
**Created:** [November 8, 2023, 12:39am UTC](https://www.isharkfly.com/t/java/15114 "2023-11-08T00:39:48Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [November 8, 2023, 12:39am UTC](https://www.isharkfly.com/t/java/15114/1 "2023-11-08T00:39:48Z")

</div>

什么是阿姆斯特朗数？

如果一个n位正整数等于其各位数字的n次方之和，则称该数为阿姆斯特朗数。

例如1^3 + 5^3 + 3^3 = 153

当n=3时，又称水仙花数，特指一种三位数，其各个数之立方和等于该数。

水仙花数共有4个，分别为：153、370、371、407。

 ![pasted image 0](https://cdn.isharkfly.com/com-isharkfly-www/discourse-uploads/original/2X/5/50df734204efc80d84f9a5c4bad11cd1d4c0ea85.png)

如果是 4 位的阿姆斯特朗数的计算方法。

 ![pasted image 0 (1)](https://cdn.isharkfly.com/com-isharkfly-www/discourse-uploads/original/2X/a/a81794c2ad3864f04b47af1c2d6eeff6778d40b7.png)

## Java 实现

可以用下面的 Java 代码来进行实现，实现的过程也非常简单，只需要对数字进行拆分就好了。

```auto
package edu.nec.course.week4.homework;

import java.util.Scanner;

public class ArmstrongNumber {

    public static void main(String args[]) {

        System.out.print("Enter starting integer: ");

        Scanner keyb = new Scanner(System.in);
        int n = keyb.nextInt();
        keyb.close();

        int y, c = 0, d = 0;
        int x = n;

        while (x > 0) {

            // modulus gives right-most digit
            y = x % 10;
            // divide gives remaining left digits
            x = x / 10;

            // tracking number of digits in number
            d++;

            System.out.println("digit is : " + y);

            //logic to calculate total of cubes of digit
            c = c + (y * y * y);

        }

        System.out.println("Total positive digits: " + d);
        System.out.println("Total sum is: " + c);

        //logic to determine if Armstrong Number
        if (c == n) {
            System.out.println(n + " IS an armstrong number");

        } else {

            System.out.println(n + " is NOT an armstrong number");
        }

    }

}

```

## 扩展

从上面的代码上，我们可以看到我们是如何对数字进行计算的。

首先把数字进行拆分，获得一个一个的数字，然后对获得数字单独进行计算，最后求和判断数字是否相等。

这里还有其他的解决方案，就是可以把给出的数字进行拆分成字符串，这个时候我们可以用到 Java 中的字符串拆分函数即可。
