Skip to content

Update Armstrong.java #6131

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 13, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions src/main/java/com/thealgorithms/maths/Armstrong.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
* An Armstrong number is often called a Narcissistic number.
*
* @author satyabarghav
* @modifier rahul katteda - (13/01/2025) - [updated the logic for getting total number of digits]
*/
public class Armstrong {

Expand All @@ -20,14 +21,16 @@ public class Armstrong {
* @return {@code true} if the given number is an Armstrong number, {@code false} otherwise
*/
public boolean isArmstrong(int number) {
if (number < 0) {
return false; // Negative numbers cannot be Armstrong numbers
}
long sum = 0;
String temp = Integer.toString(number); // Convert the given number to a string
int power = temp.length(); // Extract the length of the number (number of digits)
int totalDigits = (int) Math.log10(number) + 1; // get the length of the number (number of digits)
long originalNumber = number;

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

Expand Down
Loading