The problem asks 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 each raised to the power of the number of digits.
Approach:
The solution uses a straightforward approach:
Determine the number of digits: We first find the number of digits (k
) in the input integer n
. This can be done efficiently by converting the integer to a string and getting its length or using a loop to repeatedly divide by 10 until the number becomes 0.
Calculate the sum of powers: We iterate through the digits of the number. For each digit, we raise it to the power of k
and add it to a running sum s
. The modulo operator (%
) is used to extract each digit, and integer division (//
or /
) is used to remove the processed digit.
Check for Armstrong property: Finally, we compare the calculated sum s
with the original number n
. If they are equal, the number is an Armstrong number, and we return true
; otherwise, we return false
.
Time Complexity Analysis:
The time complexity is determined by the number of times we iterate through the digits of the number. In the worst case, this is proportional to the number of digits in n
. The number of digits is logarithmic with respect to the value of n
(approximately log10(n)). Therefore, the time complexity is O(log n).
Space Complexity Analysis:
The space complexity is constant, O(1), because we only use a few variables to store the number of digits, the sum, and the temporary variables during the iteration. We don't use any data structures whose size scales with the input. While the toString()
method in some languages might use temporary string space, this is generally considered a constant overhead.
Code Examples:
The provided code solutions demonstrate this approach in several programming languages. They all follow the same core logic described above. Slight variations might exist due to language-specific features (e.g., different ways to convert a number to a string, different pow functions).
Example (Python):
class Solution:
def isArmstrong(self, n: int) -> bool:
k = len(str(n)) # Number of digits
s = 0
x = n
while x:
digit = x % 10
s += digit ** k
x //= 10
return s == n
The Python code efficiently calculates the number of digits using len(str(n))
and then iterates through the digits using a while
loop.
Example (Java):
class Solution {
public boolean isArmstrong(int n) {
int k = String.valueOf(n).length(); // Number of digits
int s = 0;
int x = n;
while (x > 0) {
int digit = x % 10;
s += Math.pow(digit, k);
x /= 10;
}
return s == n;
}
}
The Java code is similar, using String.valueOf(n).length()
for digit counting and a while
loop for iteration.
The other languages (C++, Go, TypeScript, JavaScript) follow a similar pattern, adapting the syntax and built-in functions according to the specific language but maintaining the same algorithmic approach and complexities.