Thursday, 19 February 2015

Java Program to check whether a Number is Amstrong or Not

Find Armstrong Number using Java

Java Code to Display the Given Number is Armstrong


                    An Armstrong number is N digit number, Which is equal to the sum of the Nth powers of its digits.The Java programme will accept a number keyboard and the whether it is Armstrong.

Program:


import java.util.Scanner;

public class Armstrong {

   public static boolean isArmstrong(int input) {
       String inputAsString = input + "";
       int numberOfDigits = inputAsString.length();
       int copyOfInput = input;
       int sum = 0;
       while (copyOfInput != 0) {
           int lastDigit = copyOfInput % 10;
           sum = sum + (int) Math.pow(lastDigit, numberOfDigits);
           copyOfInput = copyOfInput / 10;
       }
           if (sum == input) {
           return true;
       } else {
           return false;
       }
   }

   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       System.out.print("Enter a number: ");
       int inputNumber = scanner.nextInt();
       boolean result = isArmstrong(inputNumber);
       if (result) {
           System.out.println(inputNumber + " is an armstrong ");
       } else {
           System.out.println(inputNumber + " is not an armstrong ");
       }
   }
}


Output:


Enter a number: 1634
1634 is an armstrong 

No comments :

Post a Comment