Check if a Number Is an Armstrong Number
Solve this ProblemEasy10–15 min
Topics
BasicsLoopsMath
Companies
TCSInfosysWipro
An Armstrong number equals the sum of its own digits, each raised to the power of how many digits it has (153 = 1³ + 5³ + 3³). Given a non-negative integer
n, return whether it's an Armstrong number.
Both solutions need to know the digit count before they can raise anything to the right power. The two-passTwo-Pass CountingLooping once just to count the digits, then looping a second time (over a fresh copy of n) to actually sum the powers. version finds that count the straightforward way — by looping. The string-lengthString Length ShortcutReading the digit count directly from the length of n's string form, leaving only the power-sum loop to write. version gets the same count in one step, the same trick used in Count the Number of Digits in an Integer.
Test Case 1:
Input:n = 153
Output:true
Explanation:1³ + 5³ + 3³ = 1 + 125 + 27 = 153.
Test Case 2:
Input:n = 123
Output:false
Explanation:1³ + 2³ + 3³ = 1 + 8 + 27 = 36, not 123.
Test Case 3:
Input:n = 9474
Output:true
Explanation:9⁴ + 4⁴ + 7⁴ + 4⁴ = 6561 + 256 + 2401 + 256 = 9474.
Constraints
- ◆
0 ≤ n ≤ 999999
Try the Dry Run
Approach & Solutions
Two Passes — Count Digits, Then Sum Their PowersGood
An Armstrong number equals the sum of each of its own digits, each raised to the power of the total digit count. That count is needed before the sum can even be computed, so this walks the digits once just to count them, then walks them again — using a second copy of n — to build the actual sum.
Time
O(d) — d is the number of digitsSpace
O(1)Java
1class Solution {
2 public boolean isArmstrong(int n) {
3 int original = n;
4 int digitCount = 0;
5 int temp = n;
6 while (temp != 0) {
7 digitCount++;
8 temp = temp / 10;
9 }
10 int sum = 0;
11 temp = n;
12 while (temp != 0) {
13 int digit = temp % 10;
14 sum += (int) Math.pow(digit, digitCount);
15 temp = temp / 10;
16 }
17 return sum == original;
18 }
19}Digit Count via String Length — One Pass for the SumOptimal
The digit count is also just the length of n's string form — no counting loop required to find it. That leaves only one real loop in the whole function: the one that builds the power sum.
Time
O(d)Space
O(d)Java
1class Solution {
2 public boolean isArmstrong(int n) {
3 int digitCount = String.valueOf(n).length();
4 int original = n;
5 int sum = 0;
6 int temp = n;
7 while (temp != 0) {
8 int digit = temp % 10;
9 sum += (int) Math.pow(digit, digitCount);
10 temp = temp / 10;
11 }
12 return sum == original;
13 }
14}