Armstrong Number in Python

PythonServer Side ProgrammingProgramming

Suppose we have a k-digit number N. The N is an Armstrong number when the k-th power of each digit sums to N. So we have to return true if it is an Armstrong number, otherwise false.

To solve this, we will follow these steps −

  • power := number of digits
  • temp := n, res = 0
  • while temp is not 0
    • res := res + (temp mod 10) ^ power
    • temp := temp / 10 //integer division
  • if res = n, return true, otherwise false.

Example

Let us see the following implementation to get a better understanding −

 Live Demo

import math
class Solution(object):
   def poww(self,base,power):
      res = 1
      while power:
         if power & 1:
            res *= base
         base *= base
         power>>=1
      return res
   def isArmstrong(self, n):
      power =int(math.log10(n)) + 1
      temp = n
      res = 0
      while temp:
         res += (self.poww(temp%10,power))
         temp//=10
      return res == n
ob1 = Solution()
print(ob1.isArmstrong(153))

Input

153

Output

true
raja
Published on 27-Feb-2020 07:16:45
Advertisements