Friday, September 15, 2023

Java Program to find Armstrong numbers with Example

Armstrong number Example in Java
How to check if a number is an Armstrong number or not? or write a Java program to find Armstrong's number? This is a common Java interview question asked on-campus interviews and fresher-level interviews. This is also a popular Java programming exercise on various schools, colleges, and computer courses to build programming logic among Students. An Armstrong number is a 3 digit number for which the sum of cube of its digits is equal to the number itself. 

One of the popular examples of the Armstrong number is 153 as 153= 1+ 125+27 which is equal to 1^3+5^3+3^3 which is equal to the sum of cube of its digits 1, 5, and 3

One more example of the Armstrong number is 371 because it is the sum of 27 + 343 + 1 which is equal to 3^3 + 7^3 + 1^3. In this Java program example, we will see a complete code example of a Java program to check if any 3 digit number is an Armstrong number or not.

If you are going for a Java interview, then be prepared for some follow-up questions like finding prime numbers, or finding Armstrong numbers of more than 3 digits.

Btw, good knowledge of essential programming concepts, operators, algorithms, data structure, and logic is important for any software engineer, particularly to do well on technical interviews.  If you are preparing for a tech interview then you should double down on these topics. 

If you need recommendations to refresh your Data Structure and algorithm skills then I highly recommend checking out Data Structures and Algorithms: Deep Dive Using Java course on Udemy. It's a hands-on course and covers all essential data structures. It's also very affordable and you can get in just $10 on Udemy flash sales which happen every now and then.




How to check if a number is Armstrong number in Java? Solved

Here is the complete code for checking if a number is an Armstrong number or not. It uses a method called isArmstrong(int number) to implement the logic for checking if a number is Armstrong nor not.

Btw, this is not the same program as print all Armstrong numbers between 0 and 999 but you can use this logic to solve that question as well. All you need to do is loop till 1000 and check if the number is Armstrong or not. If yes then print otherwise move to the next number.

By the way, this Java program is in continuation of our earlier programming exercise like


These programs will help you to build the coding sense required to solve coding problems on interviews and your day-to-day life. It's also one of the important skills to map a new coding problem into an already known one and essential to pass the coding interview on companies like Google, Facebook, Amazon, and Microsoft.

If you are preparing for those companies then I also suggest you go through Grokking the Coding Interview: Patterns for Coding Questions on Educative, an interactive portal for coding interviews to learn some 16 useful coding patterns like Sliding Window, Two Pointers, Fast and Slow Pointers, Merge Intervals, Cyclic Sort, and Top K elements that can help you to solve zones of frequently asked coding problems. 

How to check if a number is Armstrong number in Java



Java Program to Find Armstrong Number

import java.util.Scanner;

/**
 * Simple Java Program to check or find if a number is Armstrong number or not.
 * An Armstrong number of three digit is a number whose sum of cubes of its digit is equal 
 * to its number. For example 153 is an Armstrong number 
 * of 3 digit because 1^3+5^3+3^3 or   1+125+27=153
 * @author Javin
 */
public class ArmstrongTest{

    
    public static void main(String args[]) {
    
        //input number to check if its Armstrong number
        System.out.println("Please enter a 3 digit number to find if 
                                  its an Armstrong number:");
        int number = new Scanner(System.in).nextInt();
      
        //printing result
        if(isArmStrong(number)){
            System.out.println("Number : " + number 
                   + " is an Armstrong number");
        }else{
            System.out.println("Number : " + number
                      + " is not an Armstrong number");
        }

    
    }

    /*
     * @return true if number is Armstrong number or return false
     */
    private static boolean isArmStrong(int number) {
        int result = 0;
        int orig = number;
        while(number != 0){
            int remainder = number%10;
            result = result + remainder*remainder*remainder;
            number = number/10;
        }
        //number is Armstrong return true
        if(orig == result){
            return true;
        }
      
        return false;
    } 
  
}

Output:
Please enter a 3 digit number to find if its an Armstrong number:
153
Number : 153 is an Armstrong number
Please enter a 3 digit number to find if its an Armstrong number:
153
Number : 153 is an Armstrong number
Please enter a 3 digit number to find if its an Armstrong number:
371
Number : 371 is an Armstrong number


How to find Armstrong number in Java with ExampleThat's all on How to check if a number is Armstrong in Java. It’s a pretty simple Java program and if you look closely it just gets digit by digit by using the remainder operator and reduces the number by 1 digit after dividing it by 10. Let me know if you find any bug on this Java program to check for the Armstrong number.

Other Programming Interview problems you may like to solve
  • How to reverse a String in place in Java? (solution)
  • How to find all permutations of a given String in Java? (solution)
  • How to find a missing value from an array containing 1 to 100? (solution)
  • How to check if the given string is palindrome or not in Java? (solution)
  • How to find the highest occurring word from a text file in Java? (solution)
  • 100+ Data Structure and Algorithms Problems (solved)
  • 10 Books to learn Data Structure and Algorithms (books)
  • How to check if two given Strings are Anagram in Java? (solution)
  • 10 Data Structure and Algorithms course to crack coding interview (courses)
  • How to check if a String contains duplicate characters in Java? (solution)
  • How to count vowels and consonants in a given String in Java? (solution)
  • How to remove duplicate characters from String in Java? (solution)
  • How to check if a given number is prime or not? (solution)
  • 10 Free Courses to learn Data Structure and Algorithms (courses)
  • 101 Coding Problems and few tips for Tech interviews (tips)
  • When to use ArrayList vs LinkedList in Java? (answer)
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)
  • How to convert a linked list to an array in Java? (example)
  • My favorite free courses to learn data Structure in-depth (FreeCodeCamp)
  • Top 5 Books to Learn Data Structure and Algorithms (books)
  • How to count the number of leaf nodes in a given binary tree in Java? (solution)
  • Top 5 Books for Programming and Coding Interviews (books)
  • How to find the first and last element of a linked list in Java? (solution)
  • How to search elements inside a linked list in Java? (solution)
  • What is the difference between LinkedList and ArrayList in Java? (answer)
  • 21 String coding Problems from Technical Interviews (questions)
  • How to reverse words in a given String in Java? (solution)

Thanks for reading this article so far. If you find this logic-based Java coding problem from Google and my explanation useful then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are preparing for a programming job interview, then you must prepare for an all-important topic like data structure, String, array, etc. One course which can help you with this task is the Grokking the Coding Interview: Patterns for Coding Questions course. It contains popular coding interview patterns which will help you to solve most of the problems in your coding interviews.

By the way, What is your favorite Java coding exercise? Palindrom, Prime Number, Producer consumer problem , or this one?  Do let me know in comments. 

11 comments:

  1. Good tutorial, How to find Armstrong number with more than 3 digits ?

    ReplyDelete
    Replies
    1. /*
      Simple Java Program to check or find if a number is Armstrong number or not.
      [ An Armstrong number of any number of digit is a number whose sum of each digits raised to the power the total no. of digits is equal to it (the original number). For example, 9474 is an Armstrong number of 4 digits because 9^4 + 4^4 + 7^4 + 4^4 = 6561 + 256 + 2401 = 9474 ]
      */

      import java.io.*;
      import java.util.*;

      public class ArmstrongNumber
      {
      public static void main(String args[])
      {

      // Input number to check if its Armstrong number
      System.out.println("Please enter a number to find if it is an Armstrong number: ");
      int number = new Scanner(System.in).nextInt();

      // Printing result
      if(isArmStrong(number))
      {
      System.out.println(number + " is an Armstrong number");
      }
      else
      {
      System.out.println(number + " is not an Armstrong number");
      }

      } // End of main()

      // Function returning true if number is Armstrong number or returning false

      private static boolean isArmStrong(int number)
      {
      int result = 0;
      int dc=0;
      int orig = number;
      while(orig != 0)
      {
      dc++;
      orig = orig/10;
      }
      orig = number;
      while (orig!=0)
      {
      result = result + (int)Math.pow(orig%10, dc);
      orig = orig/10;
      }
      if(number == result)
      return true;
      else
      return false;
      } // End of isArmStrong()
      }

      OUTPUT:
      Please enter a number to find if it is an Armstrong number:
      9474
      9474 is an Armstrong number

      Please enter a number to find if it is an Armstrong number:
      8208
      8208 is an Armstrong number

      Delete
    2. package com.example.test.nover;
      import java.util.List;
      import java.util.ArrayList;
      public class ArmstrongNumber {

      public void findNumber() {
      List numList = new ArrayList();
      int newNum = 0;
      String numVal= "";
      int length = 0;
      for(int i = 1000; i<=9999; i++) {
      numVal = (numVal+i).trim();
      length = numVal.length();
      for(int j=0;j<length;j++) {
      char charVal = numVal.charAt(j);
      int charNum = charVal-'0';
      charNum = (int) Math.pow(charNum,4);
      //int charNo = (int) Math.pow(charNum,4);
      newNum = newNum + charNum;
      }
      if(i==newNum)
      numList.add(i);
      newNum = 0;
      numVal="";
      }
      for(int i: numList) {
      System.out.println("NUMBERS FOUND ARE " +i);
      }
      }

      public static void main(String args[]) {
      ArmstrongNumber numVer = new ArmstrongNumber();
      numVer.findNumber();
      }
      }

      Delete
    3. Using String will generalize to find ArmStrong Number for 2 digits, 3 digits or 4 digits since we can capture the length and use Math.pow(number,length) which will make the code generic.

      Delete
  2. According to Abhirupa Mitra's code numbers from 1 to 9 would be displayed as Armstrong numbers which is not correct. What is the correct definition of Armstrong numbers? Within 1 to 10 only 1 is an armstrong number.

    ReplyDelete
    Replies
    1. Yes, you are right. The correct definition of Armstrong number is:-
      ex. 153. if 1^3+5^3+3^3 = 153 then it is an Armstrong number. In words, a number whose sum is equal to the sum of the cubes of its digits then it is an Armstrong number

      Delete
  3. The definition of an Armstrong Number was not that clear to me. I looked up here and figured out what it is: http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/arms.html

    ReplyDelete
  4. I'd probably do it like this:

    public boolean isArmstrong(int i) {
    return (i >= 100) && (i <= 999) && (sumCubeDigits(i) == i);
    }

    private int sumCubeDigits(int digits) {
    if (digits == 0)
    return 0;
    else
    return cube(digits % 10) + sumCubeDigits(digits / 10);
    }

    private int cube(int i) {
    return i * i * i;
    }

    and if it turned out to be too slow, like this:

    public boolean isArmstrong(int i) {
    if ((i < 100) || (i > 999)) {
    return false;
    } else {
    int a = i % 10;
    int b = (i / 10) % 10;
    int c = i / 100;
    int sumOfCubes = (a*a*a) + (b*b*b) + (c*c*c);
    return (i == sumOfCubes);
    }
    }

    ReplyDelete
  5. I'd do it like this....

    public static void armstrong(int number){
    String numToString = String.valueOf(number);
    int number1;
    int multiplication = 0;
    for (int i=0; i<=numToString.length()-1; i++){
    number1 = Character.getNumericValue(numToString.charAt(i));
    multiplication = multiplication + number1 * number1 * number1;
    }
    if (number == multiplication) {
    System.out.println("Number : " + number + " is an Armstrong number");
    } else {
    System.out.println("Number : " + number + " is not an Armstrong number");
    }
    }

    ReplyDelete
  6. Hi All,

    Just generalised the very first answer while trying to solve Armstrong example. Hope it is useful :)

    import java.util.Scanner;

    public class ArmstrongNumbers {

    public static void main(String[] args) {
    System.out.println("Hello Enter your number");
    Scanner sc=new Scanner(System.in);
    Long n=sc.nextLong();
    Long orignal=n;
    System.out.println("Your number is - "+n);


    long rem;
    long result=0;
    String forLength=n.toString();
    int length = String.valueOf(forLength).length();
    System.out.println("Length "+length);


    while(n!=0){
    rem=n%10;
    System.out.println("Rem "+rem);
    result=(long) (result+Math.pow(rem, length));
    System.out.println("Result " +result);
    n=n/10;
    }
    if(result == orignal){
    System.out.println("Armstrong");
    }
    else{
    System.out.println("Not Armstrong");
    }
    }

    }

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.