Problem Statement

You are given an integer n. You need to check whether it is an armstrong number or not. Return true if it is an armstrong number, otherwise return false.

An armstrong number is a number which is equal to the sum of the digits of the number, raised to the power of the number of digits.

Examples

Example 1:

Input: n = 153
Output: true

Explanation: Since the number of digits is 3
then 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153
Therefore, it is an Armstrong number.
Example 2:

Input: 51
Output = false

Explanation: Since the number of digits is 2
then 5*5 + 1*1 = 25 + 1 = 26
Therefore, it is not an Armstrong number.

Approaches

1️⃣ Extraction of Digit

Intuition:

Given a number, the number of digits can be found. Once the number of digits is known, all the digits can be extracted one by one from the right which can be used to check whether the number is Armstrong or not.

Approach:

  1. Initialize three variables:
    1. count - to store the count of digits in the given number.
    2. sum - to store the sum of the digits of the number raised to the power of the number of digits.
    3. copy - to store the copy of the original number.
  2. Start iterating on the given number till there are digits left to extract. In each iteration, extract the last digit (using the modulus operator with 10), and add the digit raised to the power of count to sum. Update n by integer division with 10 effectively removing the last digit.
  3. After the iterations are over, check if the copy of the original is the same as the sum stored. If found equal, the original number is an Armstrong number, else it is not.

Code:

bool isArmstrong(int n) {
        int sum = 0;
        int copy = n;
        int count = 0;
        while( n > 0) {
            int lastDigit = n%10;
            count++;
            n = n/10;
        }

        n = copy;
        while(n > 0){
            int lastDigit = n%10;
            int power = 1;
            for(int i = 1; i <= count; i++){
                power = power * lastDigit;
            }
            sum = sum + power;
            n = n/10;
        }
        return (sum == copy);
    }

Complexity Analysis:

  • Time Complexity:O(log10(N))N is being divided by 10 until it becomes zero resulting in log10(N) iterations and in each iteration constant time operations are performed.
  • Space Complexity:O(1) – Using a couple of variables i.e., constant space, regardless of the size of the input.