Armstrong Number Problem
Description
LeetCode Problem 1134.
Given an integer n, return true if and only if it is an Armstrong number.
The k-digit number n is an Armstrong number if and only if the k^th power of each digit sums to n.
Example 1:
Input: n = 153
Output: true
Explanation: 153 is a 3-digit number, and 153 = 1^3 + 5^3 + 3^3.
Example 2:
Input: n = 123
Output: false
Explanation: 123 is a 3-digit number, and 123 != 1^3 + 2^3 + 3^3 = 36.
Constraints:
1 <= n <= 10^8
Solution
Approach: Sum the Digit Powers
First find k, the number of digits of n, for example the length of its decimal string. Then take the digits off one at a time with x % 10 and x / 10, add each digit raised to the power k, and compare the sum with n.
The power is computed with integer multiplication rather than a floating-point pow, whose result can come back a hair too low (say 124.99999) and become one less when converted to an integer. For an 8-digit n the sum is at most 8 · 98 ≈ 3.4 · 108, which fits in 32 bits; Java and C++ still keep it in a 64-bit integer to be safe.
Complexity: O(d2) time for the d digits (d <= 9, so constant in practice) and O(1) extra space.
class Solution:
def isArmstrong(self, n: int) -> bool:
k = len(str(n)) # number of digits
total, x = 0, n
while x > 0:
total += (x % 10) ** k
x //= 10
return total == n