Java for loop find Armstrong number

Introduction

An Armstrong number is an integer.

The sum of the cubes of its digits is equal to the number itself.

For example, 371 is an Armstrong number since 333 + 777 + 111 = 371.

public class Main {
  public static void main(String[] args) {
    System.out.println(1 + " is armstrong? " + isArmstrongNumber(1));
    System.out.println(153 + " is armstrong? " + isArmstrongNumber(153));
    System.out.println(371 + " is armstrong? " + isArmstrongNumber(371));
  }//from  w ww . j  a va 2s  .com

  public static boolean isArmstrongNumber(int number) {
    int sum = 0;
    int n = number;
    for (; n > 0;) {
      // get the last digit
      int digit = n % 10;
      // cube me please and sum
      sum = sum + (digit * digit * digit);
      // and remove the digit we processed.
      n = n / 10;
    }
    return number == sum;
  }
}



PreviousNext

Related