Wednesday, 12 August 2015

Armstrong Number

package com.JavaInterview.Programs;

import java.util.*;

/**
 * Find Out Factorial of a number
 * 
 * @author:http://javainterviewprograms.blogspot.in/
 * 
 */

/*Armstrong Number :sum of its digit power number of digits*
 * 371=pow(3,3)+pow(7,3)+pow(1,3)*/
public class ArmstrongNumber {

 public boolean isArmstrong(int number) {
  int tmpNumber = number;
  int noOfDigits = String.valueOf(number).length();
  int sum = 0;
  int div = 0;

  while (tmpNumber > 0) {
   div = tmpNumber % 10;
   sum = sum + (int) (Math.pow(div, noOfDigits));
   tmpNumber = tmpNumber / 10;
  }

  if (sum == number) {
   return true;
  } else {
   return false;
  }

 }

 public static void main(String args[]) {
  ArmstrongNumber AN = new ArmstrongNumber();
  Scanner input = new Scanner(System.in);

  System.out.println("Please enter the number");
  int number = input.nextInt();
  System.out.println("the number " + number + " is Armstrong Number ? :"
    + AN.isArmstrong(number) + ".");
 }

}

Output :
Please enter the number
371

the number 371 is Armstrong Number ? :true.


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...