Similar Problems

Similar Problems not available

Armstrong Number - Leetcode Solution

Companies:

LeetCode:  Armstrong Number Leetcode Solution

Difficulty: Easy

Topics: math  

Armstrong Number Problem on LeetCode:

The Armstrong number problem is a classic problem in which we have to check whether a number is an Armstrong number or not. The problem statement is as follows:

"Given a positive integer n, determine if it is an Armstrong number. An Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits. For example, 371 is an Armstrong number since 37 + 73 + 13 = 371."

Solution:

To solve the Armstrong number problem on LeetCode, we can follow a simple approach:

  1. Calculate the number of digits in the given number.
  2. Calculate the sum of nth powers of each digit in the given number.
  3. Check whether the sum obtained in step 2 is equal to the given number.

Let's see the code implementation of the above approach:

class Solution { public: bool isArmstrong(int n) { int num = n, sum = 0; int count = to_string(n).size(); // Calculate the number of digits in the given number while(num > 0) { int digit = num % 10; // Get the last digit of the number sum += pow(digit, count); // Calculate the nth power of the digit and add it to sum num /= 10; // Remove the last digit from the number } return sum == n; // Check whether the sum is equal to the given number or not } };

In the above code, we first calculate the number of digits in the given number using the to_string() function. Then, we loop through the number and calculate the nth power of each digit using the pow() function and add it to the sum. Finally, we check whether the sum is equal to the given number or not and return the result.

Time Complexity:

The time complexity of the above solution is O(log n) as we are looping through the digits of the given number.

Space Complexity:

The space complexity of the above solution is O(1) as we are not using any extra space.

Armstrong Number Solution Code

1