Determining if a number is an Armstrong number by extracting its digits.
The original problem is here.
To check this programmatically, we require three pieces of information: the individual digits, the total number of digits ($k$), and their computed sum.
str(n). Python’s built-in type casting.n % 10) and strip digits using integer division (n // 10).class Solution:
def isArmstrong(self, n: int) -> int:
# Convert integer to string to easily count and iterate over digits
n_str = []
while n > 0:
n_str.append(n % 10)
n //= 10
k = len(n_str)
# Generator expression to calculate the sum of the digits raised to the power of k
total_sum = sum(int(digit) ** k for digit in n_str)
# Check if the calculated sum matches the original number
return total_sum == n
class Solution:
def isFactorion(self, n: int) -> bool:
# Convert integer to string to easily count and iterate over digits
n_str = []
while n > 0:
n_str.append(n % 10)
n //= 10
k = len(n_str)
if 9! * k < 10**(k-1):
return False
# Generator expression to calculate the sum of the digits raised to the power of k
total_sum = sum(int(digit) ** k for digit in n_str)
# Check if the calculated sum matches the original number
return total_sum == n