Armstrong Number

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def isArmstrong(self, n: int) -> bool:
        # Convert the integer into string to find the number of digits (k)
        num_str = str(n)
        k = len(num_str)

        # Initialize a variable to store the sum
        sum_of_powers = 0

        # Go through each digit of the number
        for digit_str in num_str:
            # Convert the digit back to integer
            digit_int = int(digit_str)
            
            # Add the k-th power of the digit to the sum
            sum_of_powers += digit_int ** k

        # Check if the sum equals the original number
        return n == sum_of_powers

The function isArmstrong first converts the integer n into a string to find the number of digits (k). Then, it initializes a variable sum_of_powers to store the sum of the k-th powers of each digit.

The function then goes through each digit in the number. For each digit, it converts the digit back into an integer, calculates the k-th power of the digit, and adds it to sum_of_powers.

Finally, the function checks if sum_of_powers is equal to n. If they are equal, the number is an Armstrong number, and the function returns True. Otherwise, it returns False.

excerpt: This covers the basic building blocks such as Modulo Operator, Sum Accumulator and Reducing Input by Integer Division.

Armstrong number is a number where the sum of cubes of digits of number is equal to the number itself.

Example:

370 = 3*3*3 + 7*7*7 + 0*0*0
    = 27 + 343 + 0
    = 370

Task Breakdown

  1. Extract every digit in the given number
  2. Cube every digit
  3. Add it to running sum

First task can be implemented as follows:

First Task

1
2
3
4
5
6
7
8
9
def armstrong?(n)
  copy = n

  while copy != 0
    digit = copy % 10
    p digit
    copy = copy / 10
  end
end

Iteration 1

We can modify the program to calculate the sum:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def armstrong?(n)
  copy = n
  sum = 0

  while copy != 0
    digit = copy % 10
    sum += digit
    copy = copy / 10
  end
  sum
end

The final iteration now checks for Armstrong number:

Iteration 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def armstrong?(n)
  copy = n
  sum = 0

  while copy != 0
    digit = copy % 10
    sum += digit * digit * digit
    copy = copy / 10
  end
  
  sum == n
end

p armstrong?(370)

The input is not mutated, copy variable is used to extract digits.

Building Blocks

  • Modulo Operator
  • Sum Accumulator
  • Reducing Input by Integer Division