Python Program to Add Digits of a Number.

Given a number num, write a Python program to add digits of the given number and print the sum as an output.

Example:

Input: num = 145
Output: 10

Explanation: 1 + 4 + 5 = 10

Input: num = 9231
Output: 15

Explanation: 9 + 2 + 3 + 1 = 15

There are multiple approaches by which we can solve this problem, let's discuss each of them one by one.

Approach 1: Using integer division and modulo operator.

In this approach, we use the modulo operator % to extract the last digit of the number and add it to the sum variable. We then use integer division // to remove the last digit from the number and repeat the process until the number becomes zero.

Python code:
# Python program to add digits of a number
def add_digits(n):
    sum = 0
    while n > 0:
        sum += n % 10
        n = n // 10
    return sum

# take input from the user
num = int(input("Enter a number: "))  

print(add_digits(num))    
Output:
Enter a number: 123
6
  • Time Complexity: O(number of digits)
  • Space Complexity: O(1)

Approach 2: Using string conversion and for loop.

In this approach, we first convert the number to a string and then use a for loop to iterate over each character in the string. We convert each character back to an integer and add it to the sum variable.

Python code:
# Python program to add digits of a number
def add_digits(n):
    n = str(n)
    sum = 0
    for digit in n:
        sum += int(digit)
    return sum

# take input from the user
num = int(input("Enter a number: "))  

print(add_digits(num))    
Output:
Enter a number: 4753
19
  • Time Complexity: O(number of digits)
  • Space Complexity: O(1)

Approach 3: Using Recursion.

In this approach, we use recursion, to sum up, the digits of the number. The base case is when the number becomes zero, in which case we return zero. Otherwise, we extract the last digit using the modulo operator and add it to the result of the recursive call to add_digits with the number divided by 10.

Python Code:
# Python program to add digits of a number
def add_digits(n):
    if n == 0:
        return 0
    return n % 10 + add_digits(n // 10)

# take input from the user
num = int(input("Enter a number: "))  

print(add_digits(num))    
Output:
Enter a number: 542
11
  • Time Complexity: O(number of digits)
  • Space Complexity: O(n) 

Read more:

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS