Coding Interview

coding interview questions part 1

Pinterest LinkedIn Tumblr

Armstrong Number

An Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits
Armstrong numbers are those numbers in which sum of cube of all digits provides the same number.
Example:-
153
1^3 = 1
5^3 = 125
3^3 = 27
1^3 + 5^3 + 3^3
= 1 + 125 + 27
= 153

Source Code

package com.dsacode.Probelms;

public class ArmstrongNumer {

	public static boolean isArmStrong(int num) {
        int result = 0;
        int orig = num;
        
        while(num != 0){
            int remainder = num%10;
            result = result + remainder*remainder*remainder;
            num = num/10;
        }
        
        if(orig == result){
            return true;
        }
        
        return false;
    } 
	
	public static void main(String[] args) {
		
		if(isArmStrong(153))
			System.out.println("153 is an Armstrong Number! ");
		else
			System.out.println("153 is not an Armstrong Number! " );
		
		if(isArmStrong(12))
			System.out.println("12 is an Armstrong Number! ");
		else
			System.out.println("12 is not an Armstrong Number! " );

	}
}
#include "stdafx.h"

#include< iostream>

using namespace std;

bool isArmStrong(int num) {
	int result = 0;
	int orig = num;

	while (num != 0){
		int remainder = num % 10;
		result = result + remainder*remainder*remainder;
		num = num / 10;
	}

	if (orig == result){
		return true;
	}

	return false;
}

int _tmain(int argc, _TCHAR* argv[])
{
	if (isArmStrong(153))
		cout << "153 is an Armstrong Number! " << endl;
	else
		cout << "153 is not an Armstrong Number!" << endl;

	if (isArmStrong(12))
		cout << "12 is an Armstrong Number!" << endl;
	else
		cout << "12 is not an Armstrong Number! " << endl;

	
	return 0;
}

Output

153 is an Armstrong Number!
12 is not an Armstrong Number!

Algorithm Explanation

Take each digit from given number.
Take a cube of each digit and take summation.
Check whether the original number and sum of all digits are equal. If equal, the number is Armstrong number.
1 2 3 4 5

Write A Comment