Armstrong Number Java Program | ISC Computer Science 2019 Theory

Design a class ArmNum to check if a given number is an Armstrong number or not. A number is said to be Armstrong if the sum of its digits raised to the power of length of the number is equal to the number.

Example:
371 = 33 + 73 + 13
1634 = 14 + 64 + 34 + 44
54748 = 55 + 45 + 75 + 45 + 85
Thus 371, 1634 and 54748 are all examples of Armstrong numbers.

Some of the members of the class are given below:

Class name: ArmNum
Data members/instance variables:
n: to store the number
l: to store the length of the number
Methods/Member functions:
ArmNum(int nn): parameterized constructor to initialize the data member n = nn
int sum_pow(int i): returns the sum of each digit raised to the power of the length of the number using recursive technique. eg. 34 will return 32 + 42 (as the length of the number is 2)
void isArmstrong(): checks whether the given number is an Armstrong number by invoking the function sum_pow() and displays the result with an appropriate message

Specify the class ArmNum giving details of the constructor(), int sum_pow(int) and void isArmstrong(). Define a main() function to create an object and call the functions accordingly to enable the task.

import java.util.Scanner;
class ArmNum{
    int n;
    int l;
    public ArmNum(int nn){
        n = nn;
        l = String.valueOf(n).length();
    }
    public int sum_pow(int i){
        if(i < 10)
            return (int)Math.pow(i, l);
        return (int)Math.pow(i % 10, l) + sum_pow(i / 10);
    }
    public void isArmstrong(){
        if(n == sum_pow(n))
            System.out.println("ARMSTRONG NUMBER");
        else
            System.out.println("NOT AN ARMSTRONG NUMBER");
    }
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number: ");
        int num = Integer.parseInt(in.nextLine());
        ArmNum obj = new ArmNum(num);
        obj.isArmstrong();
    }
}