LeetCode 1134. Armstrong Number

Description

https://leetcode.com/problems/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.

Given a positive integer N, return true if and only if it is an Armstrong number.

Example 1:

Input: 153
Output: true
Explanation: 
153 is a 3-digit number, and 153 = 1^3 + 5^3 + 3^3.

Example 2:

Input: 123
Output: false
Explanation: 
123 is a 3-digit number, and 123 != 1^3 + 2^3 + 3^3 = 36.

Note:

  1. 1 <= N <= 10^8

Explanation

Compares the formula calculated number with the original number.

Python Solution

class Solution:
    def isArmstrong(self, N: int) -> bool:
        length = len(str(N))
        
        result = 0
        N_copy = N
        while N_copy > 0:
            result += (N_copy % 10) ** length
            N_copy = N_copy // 10
            
        
        return result == N
  • Time Complexity: O(N)
  • Space Complexity: O(1)

Leave a Reply

Your email address will not be published.