返回介绍

solution / 1100-1199 / 1134.Armstrong Number / README_EN

发布于 2024-06-17 01:03:23 字数 3090 浏览 0 评论 0 收藏 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 $k$th 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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文