From d2ea630bdd35980b658fc27769c51f313ecd4f06 Mon Sep 17 00:00:00 2001 From: Patient_Pace_Coder <104113247+Patient-Pace-Coder@users.noreply.github.com> Date: Mon, 13 Jan 2025 00:27:28 +0530 Subject: [PATCH] Update Armstrong.java Optimized Armstrong number check by removing string conversion --- src/main/java/com/thealgorithms/maths/Armstrong.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/thealgorithms/maths/Armstrong.java b/src/main/java/com/thealgorithms/maths/Armstrong.java index ff4ae027a0b7..5a1a5f051f8f 100644 --- a/src/main/java/com/thealgorithms/maths/Armstrong.java +++ b/src/main/java/com/thealgorithms/maths/Armstrong.java @@ -21,16 +21,14 @@ public class Armstrong { */ public boolean isArmstrong(int number) { 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 the number of digits and added to the sum. originalNumber /= 10; } - return sum == number; } }