LeetCode 1134. Armstrong Number Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1134. Armstrong Number

Description

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 kth power of each digit sums to n.

 

Example 1:

Input: n = 153
Output: true
Explanation: 153 is a 3-digit number, and 153 = 13 + 53 + 33.

Example 2:

Input: n = 123
Output: false
Explanation: 123 is a 3-digit number, and 123 != 13 + 23 + 33 = 36.

 

Constraints:

  • 1 <= n <= 108

Solutions

Solution 1: Simulation

We can first calculate the number of digits k, then calculate the sum s of the kth power of each digit, and finally check whether s equals n.

The time complexity is O(log n), and the space complexity is O(log n). Here, n is the given number.

PythonJavaC++GoTypeScriptJavaScript
class Solution: def isArmstrong(self, n: int) -> bool: k = len(str(n)) s, x = 0, n while x: s += (x % 10) ** k x //= 10 return s == n(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !