Skip to content

Files

Latest commit

9324b58 · Jun 15, 2023

History

History
This branch is 2 commits ahead of, 2993 commits behind doocs/leetcode:main.

1134.Armstrong Number

English Version

题目描述

给你一个整数 n ,让你来判定他是否是 阿姆斯特朗数,是则返回 true,不是则返回 false

假设存在一个 k 位数 n ,其每一位上的数字的 k 次幂的总和也是 n ,那么这个数是阿姆斯特朗数 。

 

示例 1:

输入:n = 153
输出:true
示例: 
153 是一个 3 位数,且 153 = 13 + 53 + 33

示例 2:

输入:n = 123
输出:false
解释:123 是一个 3 位数,且 123 != 13 + 23 + 33 = 36。

 

提示:

  • 1 <= n <= 108

解法

方法一:模拟

我们可以先计算出数字的位数 k ,然后计算每一位上的数字的 k 次幂的总和 s ,最后判断 s 是否等于 n 即可。

时间复杂度 O ( log n ) ,空间复杂度 O ( log n ) 。其中 n 为给定的数字。

Python3

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

Java

class Solution {
    public boolean isArmstrong(int n) {
        int k = (n + "").length();
        int s = 0;
        for (int x = n; x > 0; x /= 10) {
            s += Math.pow(x % 10, k);
        }
        return s == n;
    }
}

C++

class Solution {
public:
    bool isArmstrong(int n) {
        int k = to_string(n).size();
        int s = 0;
        for (int x = n; x; x /= 10) {
            s += pow(x % 10, k);
        }
        return s == n;
    }
};

Go

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
}

JavaScript

/**
 * @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;
};

TypeScript

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;
}

...