1. Calculate k by Converting to String

class Solution:
    def isArmstrong(self, n: int) -> bool:
        def getSumOfKthPowerOfDigits(num, k):
            result = 0

            while num != 0:
                result += (num % 10) ** k
                num //= 10

            return result
        
        length = len(str(n))
        
        return getSumOfKthPowerOfDigits(n, length) == n

Time & Space Complexity

  • Time complexity: O(M)O(M)

  • Space complexity: O(1)O(1) constant space

Where MM is the number of digits in the input integer n.


2. Calculate k by Using Log

class Solution:
    def isArmstrong(self, n: int) -> bool:
        def getSumOfKthPowerOfDigits(num, k):
            result = 0

            while num != 0:
                result += (num % 10) ** k
                num //= 10

            return result
        
        length = int(math.log10(n)) + 1
        
        return getSumOfKthPowerOfDigits(n, length) == n

Time & Space Complexity

  • Time complexity: O(M)O(M)

  • Space complexity: O(1)O(1) constant space

Where MM is the number of digits in the input integer n.


3. Calculate k Without Built-in Methods

class Solution:
    def isArmstrong(self, n: int) -> bool:
        def getSumOfKthPowerOfDigits(num, k):
            result = 0

            while num != 0:
                result += (num % 10) ** k
                num //= 10
                
            return result

        length = 0
        temp_n = n

        while temp_n != 0:
            length += 1
            temp_n //= 10
        
        return getSumOfKthPowerOfDigits(n, length) == n

Time & Space Complexity

  • Time complexity: O(M)O(M)

  • Space complexity: O(1)O(1) constant space

Where MM is the number of digits in the input integer n.