You add
Given a non-negative integer num, add the digits repeatedly until the result is a single digit.
Examples can be found on the LeetCode website.
Source: LeetCode link: leetcode-cn.com/problems/ad… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
Solution 1: cycle
We initialize result as num, add the digits of each digit, and then assign the result to result. We loop until result has one digit and return result.
public class LeetCode_258 {
public static int addDigits(int num) {
// The last return value
int result = num;
while (result >= 10) {
int temp = 0;
// Add the digits
while (result > 10) {
temp += result % 10;
result = result / 10;
}
if (result == 10) {
temp += 1;
} else {
temp += result;
}
result = temp;
}
return result;
}
public static void main(String[] args) {
System.out.println(addDigits(385)); }}Copy the code
Patience is an indomitable thing, whether gain or loss, is the most useful.