Welcome to Subscribe On Youtube
Question
Formatted question description: https://leetcode.ca/all/1134.html
1134. 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 <= N <= 10^8
Algorithm
Just follow problem description.
Code
-
public class Armstrong_Number { class Solution { public boolean isArmstrong(int N) { int sum = 0; int tmp = N; int length = Integer.toString(N).length(); while (tmp > 0){ sum += power(tmp % 10, length); tmp /= 10; } return sum == N; } private int power(int a, int b){ int res = 1; for (int i = 0; i < b; i++){ res *= a; } return res; } } }
-
// OJ: https://leetcode.com/problems/armstrong-number/ // Time: O(N) // Space: O(lgN) class Solution { public: bool isArmstrong(int n) { long sum = 0, target = n; vector<int> digits; while (n) { digits.push_back(n % 10); n /= 10; } for (int d : digits) sum += pow(d, digits.size()); return sum == target; } };
-
class Solution: def isArmstrong(self, n: int) -> bool: k = len(str(n)) s, t = 0, n while t: t, v = divmod(t, 10) s += pow(v, k) return n == s
-
func isArmstrong(n int) bool { k := 0 for x := n; x > 0; x /= 10 { k++ } s := 0 for x := n; x > 0; x /= 10 { s += int(math.Pow(float64(x%10), float64(k))) } return s == n }
-
function isArmstrong(n: number): boolean { const k = String(n).length; let s = 0; for (let x = n; x; x = Math.floor(x / 10)) { s += Math.pow(x % 10, k); } return s == n; }
-
/** * @param {number} n * @return {boolean} */ var isArmstrong = function (n) { const k = String(n).length; let s = 0; for (let x = n; x; x = Math.floor(x / 10)) { s += Math.pow(x % 10, k); } return s == n; };