Monday, 26 June 2017

Write a program to find the given number is Armstrong number or not?


Description:
Armstrong numbers are the sum of their own digits to the power of
the number of digits. It is also known as narcissistic numbers.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.govindsblog.algos;
 
public class MyArmstrongNumber {
 
    public boolean isArmstrongNumber(int number){
         
        int tmp = number;
        int noOfDigits = String.valueOf(number).length();
        int sum = 0;
        int div = 0;
        while(tmp > 0)
        {
            div = tmp % 10;
            int temp = 1;
            for(int i=0;i<noOfDigits;i++){
                temp *= div;
            }
            sum += temp;
            tmp = tmp/10;
        }
        if(number == sum) {
            return true;
        } else {
            return false;
        }
    }
     
    public static void main(String a[]){
        MyArmstrongNumber man = new MyArmstrongNumber();
        System.out.println("Is 371 Armstrong number? "+man.isArmstrongNumber(371));
        System.out.println("Is 523 Armstrong number? "+man.isArmstrongNumber(523));
        System.out.println("Is 153 Armstrong number? "+man.isArmstrongNumber(153));
    }
}

Output:
Is 371 Armstrong number? true
Is 523 Armstrong number? false
Is 153 Armstrong number? true

No comments:

Post a Comment