The Armstrong Number problem asks you to determine if a given integer n
is an Armstrong number. An Armstrong number is a number that is equal to the sum of its own digits raised to the power of the number of digits.
153
is an Armstrong number because 13 + 53 + 33 = 153
.7
, it is always an Armstrong number because 71 = 7
.Constraints:
n
.true
if n
is an Armstrong number, and false
otherwise.To solve this problem, you need to compare the original number to the sum of its digits each raised to the power of the number of digits. The most straightforward way is to:
A brute-force approach would be to convert the number to a string, iterate over each character, convert it back to an integer, and perform the calculation. This is both easy to implement and efficient for typical input sizes.
There aren't significant optimizations needed because the number of digits in n
is small (at most 10 for 32-bit integers), so iterating over the digits is fast.
Let's break down the steps to check if a number is an Armstrong number:
true
; otherwise, return false
.This approach is both readable and efficient for all practical input sizes, and it works in any programming language.
Let's walk through the process with an example input: n = 9474
.
9474
is an Armstrong number.Brute-force approach:
O(d)
, where d
is the number of digits in n
(since we process each digit once).O(1)
if we process digits numerically; O(d)
if we convert to a string, but for small d
this is negligible.Since the number of digits in any integer is at most 10 (for 32-bit numbers), this is extremely efficient.
Optimized approach:The Armstrong Number problem is a classic example of digit manipulation. The solution is elegant because it leverages simple arithmetic and string processing to check a property of numbers. By breaking the number into digits, raising each to the appropriate power, and summing, we can efficiently determine if a number is an Armstrong number. The approach is both easy to implement and efficient for any reasonable input.
class Solution:
def isArmstrong(self, n: int) -> bool:
digits = [int(d) for d in str(n)]
k = len(digits)
return sum(d ** k for d in digits) == n
class Solution {
public:
bool isArmstrong(int n) {
int num = n, k = 0;
while (num) {
k++;
num /= 10;
}
num = n;
int sum = 0;
while (num) {
int digit = num % 10;
int powDigit = 1;
for (int i = 0; i < k; ++i) powDigit *= digit;
sum += powDigit;
num /= 10;
}
return sum == n;
}
};
class Solution {
public boolean isArmstrong(int n) {
int num = n, k = 0;
while (num > 0) {
k++;
num /= 10;
}
num = n;
int sum = 0;
while (num > 0) {
int digit = num % 10;
int powDigit = 1;
for (int i = 0; i < k; ++i) powDigit *= digit;
sum += powDigit;
num /= 10;
}
return sum == n;
}
}
var isArmstrong = function(n) {
const digits = n.toString().split('').map(Number);
const k = digits.length;
let sum = 0;
for (let d of digits) {
sum += Math.pow(d, k);
}
return sum === n;
};