Last updated on April 7th, 2024 at 02:34 pm
Here, We see Add Digits problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.
List of all LeetCode Solution
![Add Digits LeetCode Solution](https://i0.wp.com/totheinnovation.com/wp-content/uploads/2024/02/LeetCode-Problem-Solution.png?resize=200%2C200&ssl=1)
Add Digits LeetCode Solution
Table of Contents
Problem Statement
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Example 1: Input: num = 38 Output: 2 Explanation: The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it. Example 2: Input: num = 0 Output: 0
Add Digits Leetcode Solution C++
class Solution {
public:
int addDigits(int num) {
while(num>9){
int temp = num%10;
num = num/10 + temp;
}
return num;
}
};
Code language: C++ (cpp)
Add Digits Leetcode Solution Java
class Solution {
public int addDigits(int num) {
if(num == 0) return 0;
else if(num % 9 == 0) return 9;
else return num % 9;
}
}
Code language: Java (java)
Add Digits Leetcode Solution JavaScript
var addDigits = function(num) {
return 1 + (num - 1) % 9;
};
Code language: JavaScript (javascript)
Add Digits Leetcode Python
class Solution(object):
def addDigits(self, num):
return num if num == 0 else num % 9 or 9
Code language: Python (python)