算法:258. Add Digits 各位相加

题目

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 <= 2^31 - 1

Follow up: Could you do it without any loop/recursion in O(1) runtime?

递归解法

/*
 * @lc app=leetcode.cn id=258 lang=java
 *
 * [258] 各位相加
 */

// @lc code=start
class Solution {
    
    
    public int addDigits(int num) {
    
    
        return (num < 10) ? num : addDigits(num / 10 + num % 10);
    }
}
// @lc code=end


线性解法O(1)时间复杂度

public class Solution {
    
    
    public int addDigits(int num) {
    
    
        if (num == 0){
    
    
            return 0;
        }
        if (num % 9 == 0){
    
    
            return 9;
        }
        else {
    
    
            return num % 9;
        }
    }
}

我将尝试解释其背后的数学原理:

首先,您应该了解:

10^k % 9 = 1
a*10^k % 9 = a % 9 

然后让我们用一个例子来帮助解释。

说一个数字x = 23456

x = 2 * 10000 + 3 * 1000 + 4 * 100 + 5 * 10 + 6

2 * 100009 = 29

3 * 10009 = 39

4 * 1009 = 49

5 * 109 = 59

然后x%9 =(2+ 3 + 4 + 5 + 6)%9,请注意x = 2 * 10000 + 3 * 1000 + 4 * 100 + 5 * 10 + 6

所以我们有23456%9 =(2 + 3 + 4 + 5 + 6)%9

猜你喜欢

转载自blog.csdn.net/zgpeace/article/details/115017833