* fix doc

* add test
* fix armstrong number
This commit is contained in:
shellhub
2020-08-12 22:04:20 +08:00
parent 3cb9adfc6f
commit 2bd49e4728

View File

@ -1,49 +1,43 @@
package Others; package Others;
import java.util.Scanner;
/** /**
* A utility to check if a given number is armstrong or not. Armstrong number is * An Armstrong number is equal to the sum of the cubes of its digits.
* a number that is equal to the sum of cubes of its digits for example 0, 1, * For example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370.
* 153, 370, 371, 407 etc. For example 153 = 1^3 + 5^3 +3^3 * An Armstrong number is often called Narcissistic number.
*
* @author mani manasa mylavarapu
*/ */
public class Armstrong { public class Armstrong {
static Scanner scan;
public static void main(String[] args) { public static void main(String[] args) {
scan = new Scanner(System.in); assert (isArmStrong(0));
int n = inputInt("please enter the number"); assert (isArmStrong(1));
boolean isArmstrong = checkIfANumberIsAmstrongOrNot(n); assert (isArmStrong(153));
if (isArmstrong) { assert (isArmStrong(1634));
System.out.println("the number is armstrong"); assert (isArmStrong(371));
} else { assert (!isArmStrong(200));
System.out.println("the number is not armstrong");
}
} }
/** /**
* Checks whether a given number is an armstrong number or not. Armstrong * Checks whether a given number is an armstrong number or not.
* number is a number that is equal to the sum of cubes of its digits for
* example 0, 1, 153, 370, 371, 407 etc.
* *
* @param number * @param number number to check
* @return boolean * @return {@code true} if given number is armstrong number, {@code false} otherwise
*/ */
public static boolean checkIfANumberIsAmstrongOrNot(int number) { private static boolean isArmStrong(int number) {
int remainder, sum = 0, temp = 0; int sum = 0;
temp = number; int temp = number;
int numberOfDigits = 0;
while (temp != 0) {
numberOfDigits++;
temp /= 10;
}
temp = number; /* copy number again */
while (number > 0) { while (number > 0) {
remainder = number % 10; int remainder = number % 10;
sum = sum + (remainder * remainder * remainder); int power = 1;
number = number / 10; for (int i = 1; i <= numberOfDigits; power *= remainder, ++i) ;
sum = sum + power;
number /= 10;
} }
return sum == temp; return sum == temp;
} }
private static int inputInt(String string) {
System.out.print(string);
return Integer.parseInt(scan.nextLine());
}
} }