Skip to content

Commit 2bd49e4

Browse files
* fix doc
* add test * fix armstrong number
1 parent 3cb9adf commit 2bd49e4

1 file changed

Lines changed: 26 additions & 32 deletions

File tree

Others/Armstrong.java

Lines changed: 26 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,43 @@
11
package Others;
22

3-
import java.util.Scanner;
4-
53
/**
6-
* A utility to check if a given number is armstrong or not. Armstrong number is
7-
* a number that is equal to the sum of cubes of its digits for example 0, 1,
8-
* 153, 370, 371, 407 etc. For example 153 = 1^3 + 5^3 +3^3
9-
*
10-
* @author mani manasa mylavarapu
4+
* An Armstrong number is equal to the sum of the cubes of its digits.
5+
* For example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370.
6+
* An Armstrong number is often called Narcissistic number.
117
*/
128
public class Armstrong {
13-
static Scanner scan;
149

1510
public static void main(String[] args) {
16-
scan = new Scanner(System.in);
17-
int n = inputInt("please enter the number");
18-
boolean isArmstrong = checkIfANumberIsAmstrongOrNot(n);
19-
if (isArmstrong) {
20-
System.out.println("the number is armstrong");
21-
} else {
22-
System.out.println("the number is not armstrong");
23-
}
11+
assert (isArmStrong(0));
12+
assert (isArmStrong(1));
13+
assert (isArmStrong(153));
14+
assert (isArmStrong(1634));
15+
assert (isArmStrong(371));
16+
assert (!isArmStrong(200));
2417
}
2518

2619
/**
27-
* Checks whether a given number is an armstrong number or not. Armstrong
28-
* number is a number that is equal to the sum of cubes of its digits for
29-
* example 0, 1, 153, 370, 371, 407 etc.
20+
* Checks whether a given number is an armstrong number or not.
3021
*
31-
* @param number
32-
* @return boolean
22+
* @param number number to check
23+
* @return {@code true} if given number is armstrong number, {@code false} otherwise
3324
*/
34-
public static boolean checkIfANumberIsAmstrongOrNot(int number) {
35-
int remainder, sum = 0, temp = 0;
36-
temp = number;
25+
private static boolean isArmStrong(int number) {
26+
int sum = 0;
27+
int temp = number;
28+
int numberOfDigits = 0;
29+
while (temp != 0) {
30+
numberOfDigits++;
31+
temp /= 10;
32+
}
33+
temp = number; /* copy number again */
3734
while (number > 0) {
38-
remainder = number % 10;
39-
sum = sum + (remainder * remainder * remainder);
40-
number = number / 10;
35+
int remainder = number % 10;
36+
int power = 1;
37+
for (int i = 1; i <= numberOfDigits; power *= remainder, ++i) ;
38+
sum = sum + power;
39+
number /= 10;
4140
}
4241
return sum == temp;
4342
}
44-
45-
private static int inputInt(String string) {
46-
System.out.print(string);
47-
return Integer.parseInt(scan.nextLine());
48-
}
4943
}

0 commit comments

Comments
 (0)