Armstrong Number
Problem
A number is an Armstrong number when the sum of its digits, each raised to the power of the number of digits, equals the number itself. Read one integer and print true if it is an Armstrong number, otherwise print false. Negative numbers are never Armstrong numbers.
Constraints
- -10^9 <= number <= 10^9
Examples
Input
153
Output
true
Input
123
Output
false
Solutions
We take the last digit with % 10, add digit^d to a sum, and remove the digit with / 10. We use long for the sum so large powers do not overflow.
/*
* Problem : Check if a number is an Armstrong number.
* Input : One integer, for example 153.
* Output : true or false.
* Approach: Split the number into digits and add each digit raised to the power of the digit count.
* Time : O(d) where d is the number of digits.
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method receives a number and returns true if it is an Armstrong number.
static boolean isArmstrong(int number) {
// Step 1: A negative number is not an Armstrong number.
if (number < 0) {
return false;
}
// Step 2: Save the original number because we change "remaining" in the loop.
int remaining = number;
// Step 3: Count the digits. Example: 153 has 3 digits. Zero has 1 digit.
int digitCount = String.valueOf(number).length();
// Step 4: Start the sum with 0.
long sum = 0;
// Step 5: Repeat until no digits are left.
while (remaining > 0) {
// Step 5a: Take the last digit. Example: 153 % 10 = 3.
int digit = remaining % 10;
// Step 5b: Raise the digit to the power of the digit count and add it to the sum.
long power = 1;
for (int i = 0; i < digitCount; i++) {
power = power * digit;
}
sum = sum + power;
// Step 5c: Remove the last digit. Example: 153 / 10 = 15.
remaining = remaining / 10;
}
// Step 6: The number is an Armstrong number if the sum equals the original number.
return sum == number;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
System.out.println(isArmstrong(number));
}
}
Hints (3)
- Think about how to get the last digit of a number. Which operator gives the remainder?
- Count the digits first. Every digit is raised to the same power: the digit count.
- Compare the sum with the saved original number. Do not compare it with the changed number.