Skip to content

Commit d2ea630

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

File tree

1 file changed

+2
-4
lines changed

1 file changed

+2
-4
lines changed

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

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,14 @@ public class Armstrong {
2121
*/
2222
public boolean isArmstrong(int number) {
2323
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)
24+
int totalDigits = (int) Math.log10(number) + 1;; // get the length of the number (number of digits)
2625
long originalNumber = number;
2726

2827
while (originalNumber > 0) {
2928
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.
29+
sum += (long) Math.pow(digit, totalDigits); // The digit raised to the power of the number of digits and added to the sum.
3130
originalNumber /= 10;
3231
}
33-
3432
return sum == number;
3533
}
3634
}

0 commit comments

Comments
 (0)