Skip to content

Latest commit

 

History

History
93 lines (71 loc) · 1.91 KB

File metadata and controls

93 lines (71 loc) · 1.91 KB

中文文档

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

Python3

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

Java

class Solution {
    public boolean isArmstrong(int n) {
        int k = String.valueOf(n).length();
        int s = 0, t = n;
        while (t != 0) {
            s += Math.pow(t % 10, k);
            t /= 10;
        }
        return n == s;
    }
}

JavaScript

/**
 * @param {number} n
 * @return {boolean}
 */
var isArmstrong = function (n) {
    const k = String(n).length;
    let s = 0;
    let t = n;
    while (t) {
        s += Math.pow(t % 10, k);
        t = Math.floor(t / 10);
    }
    return n == s;
};

...