Last updated on January 7th, 2025 at 03:21 am
Here, we see the Add Digits LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.
List of all LeetCode Solution
Topics
Math
Companies
Adobe, Microsoft
Level of Question
Easy
Add Digits LeetCode Solution
Table of Contents
1. 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
2. Coding Pattern Used in Solution
The coding pattern used here is “Mathematical Optimization” or “Number Theory”, as it leverages properties of numbers (specifically modular arithmetic) to solve the problem efficiently.
3. Code Implementation in Different Languages
3.1 Add Digits C++
class Solution { public: int addDigits(int num) { while(num>9){ int temp = num%10; num = num/10 + temp; } return num; } };
3.2 Add Digits Java
class Solution { public int addDigits(int num) { if(num == 0) return 0; else if(num % 9 == 0) return 9; else return num % 9; } }
3.3 Add Digits JavaScript
var addDigits = function(num) { return 1 + (num - 1) % 9; };
3.4 Add Digits Python
class Solution(object): def addDigits(self, num): return num if num == 0 else num % 9 or 9
4. Time and Space Complexity
Time Complexity | Space Complexity | |
C++ | O(log(num)) | O(1) |
Java | O(1) | O(1) |
JavaScript | O(1) | O(1) |
Python | O(1) | O(1) |
- The C++ code uses an iterative approach, which is less efficient compared to the mathematical approach used in the other languages.
- The Java, JavaScript, and Python codes are optimized and use the mathematical property of the digital root:
- For any number
num
, the digital root can be computed as:num % 9
(ifnum
is not 0 or divisible by 9).- Special cases: If
num == 0
, the result is 0. Ifnum % 9 == 0
, the result is 9.
- For any number
- The mathematical approach is significantly faster (O(1)) and more space-efficient than the iterative approach (O(log(num))).