How to Determine the Armstrong Number?

  • 时间:2020-09-21 09:15:21
  • 分类:网络文摘
  • 阅读:108 次

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

Python to Check if a Integer is Armstrong

Do what it says. The solution should be quite intuitive. Two things need to be resolved: get the number of digits which could be done via converting to string and get the length or using the log10 math function. The second is to compute a^b which in Python this could be done simply by a**b.

Then, we need to extract the right-most digit by do the moduluo ten, and do the integer division using // in Python..

1
2
3
4
5
6
7
8
9
10
class Solution:
    def isArmstrong(self, N: int) -> bool:
        s = 0
        n = N
        l = len(str(N))
        while n > 0:
            t = n % 10
            n //= 10
            s = s + (t ** l)
        return s == N
class Solution:
    def isArmstrong(self, N: int) -> bool:
        s = 0
        n = N
        l = len(str(N))
        while n > 0:
            t = n % 10
            n //= 10
            s = s + (t ** l)
        return s == N

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
福建少儿频道直播-福建少儿在线直播观看「高清」  内蒙古少儿频道直播-内蒙古少儿在线直播观看「高清」  劲爆体育直播-劲爆体育在线直播观看「高清」  辽宁体育直播-辽宁体育在线直播观看「高清」  北京体育频道直播-北京体育在线直播观看「高清」  五星体育直播-五星体育在线直播观看「高清」  风云足球直播-风云足球在线直播观看「高清」  吉林篮球直播-吉林篮球在线直播观看「高清」  江苏体育直播-江苏体育在线直播观看「高清」  广州竞赛直播-广州竞赛频道在线直播观看「高清」 
评论列表
添加评论