Skip to content

Commit 2b9869b

Browse files
Update Armstrong.java
Optimized Armstrong number check by removing string conversion
1 parent bd785de commit 2b9869b

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

src/main/java/com/thealgorithms/maths/Armstrong.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
* An Armstrong number is often called a Narcissistic number.
1111
*
1212
* @author satyabarghav
13+
* @modifier rahul katteda - (13/01/2025) - [updated the logic for getting total number of digits]
1314
*/
1415
public class Armstrong {
1516

@@ -20,14 +21,16 @@ public class Armstrong {
2021
* @return {@code true} if the given number is an Armstrong number, {@code false} otherwise
2122
*/
2223
public boolean isArmstrong(int number) {
24+
if (number < 0) {
25+
return false; // Negative numbers cannot be Armstrong numbers
26+
}
2327
long sum = 0;
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)
28+
int totalDigits = (int) Math.log10(number) + 1; // get the length of the number (number of digits)
2629
long originalNumber = number;
2730

2831
while (originalNumber > 0) {
2932
long digit = originalNumber % 10;
30-
sum += (long) Math.pow(digit, power); // The digit raised to the power of the number of digits and added to the sum.
33+
sum += (long) Math.pow(digit, totalDigits); // The digit raised to the power of total number of digits and added to the sum.
3134
originalNumber /= 10;
3235
}
3336

0 commit comments

Comments
 (0)