Add Digits LeetCode Solution

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.

Add Digits LeetCode Solution

Add Digits LeetCode Solution

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)