2
头图

Add up everyone

Title description: Given a non-negative integer num, add the numbers in each digit repeatedly until the result is a single digit.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/add-digits/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution one: loop
Declare a variable result to be initialized to num, add the numbers of each digit differently, and then assign the result to the result, loop processing until the value of the result is a single digit, and finally return the result.
public class LeetCode_258 {
    public static int addDigits(int num) {
        // 最后的返回值
        int result = num;
        while (result >= 10) {
            int temp = 0;
            // 各个数位相加
            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));
    }
}
[Daily Message] Patience is an indomitable thing, no matter the gains or losses, it is the most useful.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!