# Check if the given number is Armstrong Number in Java

Carvia Tech | May 18, 2019 | 2 min read | 216 views |

Armstrong number

In an Armstrong number (also known as narcissistic number), is a number that is the sum of its own digits each raised to the power of the number of digits.

`xy...z = x^n + y^n + ... + z^n`

where n is the number of digits in a number.

Few examples are: 153, 371, 407, 8208, etc.

153 = 13 + 53 + 33
8208 = 84 + 24 + 04 + 84

## Armstrong number: Java implementation

We can write a simple Java program to check if the given input is armstrong number or not.

Here is the approach:

1. Count the number of digits in a number

2. extract digits from input number one by one using remainder operation

3. calculate the sum of powers of each digit

4. if the sum of powers is same as the input itself, then number is armstrong else not.

Armstrong.java
``````public class Armstrong {

public boolean check(int input) {
int temp, digit, sumOfPower = 0;
temp = input;
int digits = countDigit(input);
while (temp != 0) {
digit = temp % 10;
System.out.println("Current Digit is " + digit);
sumOfPower = sumOfPower + (int) Math.pow(digit, digits);
System.out.println("Current sumOfPower is " + sumOfPower);
temp /= 10;
}
return sumOfPower == input;
}

static int countDigit(long n) {
return (int) Math.floor(Math.log10(n) + 1);
}
}``````

We know that only 4 armstrong numbers that are of 3 digits (i.e. from 100 to 999), we can write a simple JUnit test to assert the same.

JUnit testcase
``````import org.junit.Test;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.*;

public class ArmstrongTest {

@Test
public void check() {
Armstrong checker = new Armstrong();
assertThat(checker.check(153), equalTo(true));
assertThat(checker.check(370), equalTo(true));
assertThat(checker.check(371), equalTo(true));
assertThat(checker.check(407), equalTo(true));
assertThat(checker.check(8208), equalTo(true));
}
}``````

That’s all.

###### Java Coding Challenges:
See all articles in Java Coding Challenges

###### Find more on this topic: ##### SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago

###### Recommended books for interview preparation:
Book you may be interested in..
Book you may be interested in..
Book you may be interested in..