Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Add Digits problem solution

YASH PAL, 31 July 2024

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;
}

coding problems

Post navigation

Previous post
Next post
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
  • Hackerrank Day 14 scope 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes