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
Approach 1: Using integer division and modulo operator.
# 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))
Enter a number: 123
6- Time Complexity: O(number of digits)
- Space Complexity: O(1)
Approach 2: Using string conversion and for loop.
# 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))
Enter a number: 4753
19- Time Complexity: O(number of digits)
- Space Complexity: O(1)
Approach 3: Using Recursion.
# 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))
Enter a number: 542
11- Time Complexity: O(number of digits)
- Space Complexity: O(n)
Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.