|
1 | 1 | package com.thealgorithms.maths;
|
2 | 2 |
|
3 | 3 | /**
|
4 |
| - * An Armstrong number is equal to the sum of the cubes of its digits. For |
5 |
| - * example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. An |
6 |
| - * Armstrong number is often called Narcissistic number. |
| 4 | + * This class checks whether a given number is an Armstrong number or not. |
| 5 | + * An Armstrong number is a number that is equal to the sum of its own digits, |
| 6 | + * each raised to the power of the number of digits. |
7 | 7 | *
|
8 |
| - * @author Vivek |
| 8 | + * For example, 370 is an Armstrong number because 3^3 + 7^3 + 0^3 = 370. |
| 9 | + * 1634 is an Armstrong number because 1^4 + 6^4 + 3^4 + 4^4 = 1634. |
| 10 | + * An Armstrong number is often called a Narcissistic number. |
| 11 | + * |
| 12 | + * @author satyabarghav |
9 | 13 | */
|
10 | 14 | public class Armstrong {
|
11 | 15 |
|
12 | 16 | /**
|
13 |
| - * Checks whether a given number is an armstrong number or not. |
| 17 | + * Checks whether a given number is an Armstrong number or not. |
14 | 18 | *
|
15 |
| - * @param number number to check |
16 |
| - * @return {@code true} if given number is armstrong number, {@code false} |
17 |
| - * otherwise |
| 19 | + * @param number the number to check |
| 20 | + * @return {@code true} if the given number is an Armstrong number, {@code false} otherwise |
18 | 21 | */
|
19 | 22 | public boolean isArmstrong(int number) {
|
20 | 23 | long sum = 0;
|
21 |
| - long number2 = number; |
22 |
| - while (number2 > 0) { |
23 |
| - long mod = number2 % 10; |
24 |
| - sum += Math.pow(mod, 3); |
25 |
| - number2 /= 10; |
| 24 | + String temp = Integer.toString(number); // Convert the given number to a string |
| 25 | + int power = temp.length(); // Extract the length of the number (number of digits) |
| 26 | + long originalNumber = number; |
| 27 | + |
| 28 | + while (originalNumber > 0) { |
| 29 | + long digit = originalNumber % 10; |
| 30 | + sum += Math.pow(digit, power); // The digit raised to the power of the number of digits and added to the sum. |
| 31 | + originalNumber /= 10; |
26 | 32 | }
|
| 33 | + |
27 | 34 | return sum == number;
|
28 | 35 | }
|
29 | 36 | }
|
0 commit comments