In this Leetcode Add Digits problem solution we have given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

Leetcode Add Digits problem solution


Problem solution in Python.

class Solution:
    def addDigits(self, num: int) -> int:
        while num > 9:
            num = num%10+ num//10
        return num



Problem solution in Java.

class Solution {
public int addDigits(int num) {
while(num>=10)
{
int rem=num%10;
int q=num/10;
int res=rem+q;
num=res;
}
return num;

}
}


Problem solution in C++.

class Solution {
public:
    int addDigits(int num) {
     int sum=0;
        while(num>0)
        {
            int last=num%10;
            sum+=last;
            num=num/10;
            if(num==0 && sum>9)
            {
                num=sum;
                sum=0;
            }
        }
        return sum;
    }
};


Problem solution in C.

int addDigits(int num){
    
    while(num/10){
        int sum = 0;
        while(num){
            sum += num%10;
            num /= 10;
        }
        num = sum;
    }
    return num;
}