Add Digits using Python

The problem of adding digits is a popular coding interview question. Here we need to add all the digits of the integer till we get to a single-digit integer. So, if you want to know how to solve this problem using Python, this article is for you. This article will take you through how to add digits using Python.

Add Digits using Python

In the problem of adding digits, you will be given an integer of more than one digit. You need to add all the digits of the integer till you get a single-digit value as the sum. Below is an example of the input and output of this problem:

Input: 38
Output: 2 (3+8 = 11, 1+1 = 2)

I hope you have understood what the problem of adding digits means. Now, below is how you can add digits using the Python programming language:

def addDigits(num):
    while num > 9:
        num = (num % 10) + (num // 10)
    return num

print(addDigits(38))
Output: 2

So this is how you can solve the problem of adding digits using Python. You can find many more practice questions for coding interviews solved and explained using Python here.

Summary

In the problem of adding digits, you will be given an integer of more than one digit. You need to add all the digits of the integer till you get a single-digit value as the sum. I hope you liked this article on how to add digits using Python. Feel free to ask valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

Coder with the ♥️ of a Writer || Data Scientist | Solopreneur | Founder

Articles: 1333

Leave a Reply