From 2b9869b252c414ed74f7482abbdbe68a44a50f01 Mon Sep 17 00:00:00 2001 From: Patient_Pace_Coder <104113247+Patient-Pace-Coder@users.noreply.github.com> Date: Mon, 13 Jan 2025 10:52:44 +0530 Subject: [PATCH] Update Armstrong.java Optimized Armstrong number check by removing string conversion --- src/main/java/com/thealgorithms/maths/Armstrong.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/thealgorithms/maths/Armstrong.java b/src/main/java/com/thealgorithms/maths/Armstrong.java index ff4ae027a0b7..9a7a014ec99f 100644 --- a/src/main/java/com/thealgorithms/maths/Armstrong.java +++ b/src/main/java/com/thealgorithms/maths/Armstrong.java @@ -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 { @@ -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; }