File tree Expand file tree Collapse file tree 1 file changed +6
-3
lines changed
src/main/java/com/thealgorithms/maths Expand file tree Collapse file tree 1 file changed +6
-3
lines changed Original file line number Diff line number Diff line change 10
10
* An Armstrong number is often called a Narcissistic number.
11
11
*
12
12
* @author satyabarghav
13
+ * @modifier rahul katteda - (13/01/2025) - [updated the logic for getting total number of digits]
13
14
*/
14
15
public class Armstrong {
15
16
@@ -20,14 +21,16 @@ public class Armstrong {
20
21
* @return {@code true} if the given number is an Armstrong number, {@code false} otherwise
21
22
*/
22
23
public boolean isArmstrong (int number ) {
24
+ if (number < 0 ) {
25
+ return false ; // Negative numbers cannot be Armstrong numbers
26
+ }
23
27
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)
26
29
long originalNumber = number ;
27
30
28
31
while (originalNumber > 0 ) {
29
32
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.
31
34
originalNumber /= 10 ;
32
35
}
33
36
You can’t perform that action at this time.
0 commit comments