Algorithm
Problem Name: 258. Add Digits
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
Constraints:
0 <= num <= 231 - 1
Code Examples
#1 Code Example with C Programming
Code -
C Programming
#include <stdio.h>
#include <assert.h>
int addDigits0(int num) {
int ans = 0;
while (num > 0) {
ans += num % 10;
num /= 10;
if (ans >= 10) {
ans = ans / 10 + ans % 10;
}
}
return ans;
}
int addDigits(int num) {
return 1 + (num - 1) % 9;
}
int main() {
assert(addDigits(0) == 0);
assert(addDigits(1) == 1);
assert(addDigits(9) == 9);
assert(addDigits(38) == 2);
assert(addDigits(12345) == 6);
printf("all tests passed!\n");
return 0;
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
int addDigits(int num) {
return num%9 ? num%9 : num ? 9 : 0;
}
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int addDigits(int num) {
if (num / 10 == 0) {
return num;
}
int digitSum = 0;
while (num > 0) {
digitSum += num % 10;
num /= 10;
}
return addDigits(digitSum);
}
}
Copy The Code &
Try With Live Editor
Input
#4 Code Example with Javascript Programming
Code -
Javascript Programming
const addDigits = function(num) {
let arr = ("" + num).split("");
let res = num;
while (arr.length > 1) {
res = arr.reduce((ac, el) => +ac + +el, 0);
arr = ("" + res).split("");
}
return +res;
};
Copy The Code &
Try With Live Editor
Input
#5 Code Example with Python Programming
Code -
Python Programming
class Solution:
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
num=str(num)
while len(num)>1:
num=str(sum([int(i) for i in num]))
return int(num)
Copy The Code &
Try With Live Editor
Input
Output
#6 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0258_AddDigits
{
public int AddDigits(int num)
{
if (num == 0) return 0;
var result = num % 9;
return result == 0 ? 9 : result;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output