【LeetCode】258. Add Digits(水题or公式)

原题

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

解答

  1. 非递归做法:
int addDigits(int num) {
    int ans = num;
    while (ans/10)
    {
        ans = 0;
        while (num)
        {
            ans += num%10;
            num /= 10;
        }
        num = ans;
    }
    return ans;
}
  1. 递归:
int addDigits(int num) {
    if (num/10 == 0)
        return num;
    int ans = 0;
    while (num)
    {
        ans += num%10;
        num /= 10;
    }
    return addDigits(ans);
}

嗯,然后以为就完了?

不!

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

没能想出来……看了答案,原来是有公式的:


这里写图片描述

详见 Wiki:https://en.wikipedia.org/wiki/Digital_root

比较佩服的还是网友们各种简洁的代码:

//公式解,一行代码
int addDigits(int num) {
    return (num && !(num %= 9)) ? 9 : num;
}
//公式解,一行代码
int addDigits(int num) {
        return 1 + (num - 1) % 9;
}
//非递归解,两行
int addDigits(int num) {
    while (num / 10) num = num / 10 + num % 10;
    return num;
}

虽然一味追求代码简短并不一定好(可能丢失可读性),但是还是可以在保证代码可读性的情况下争取代码简洁的!

实际上,上面这段两行的代码,他的思路跟我是有点不同的。

我的思路是很规矩的来加,比如:

385 -> 3+8+5 = 16 -> 1+6 = 7

而他的思路是:

385 -> 38+5 = 43 -> 4+3 = 7

为何这样做是对的呢?

主要看 38+5 与 3+8+5 的不同,38+5 将 8+5 的进位1累加到高位的3上面, 而 3+8+5将 8+5 的进位保留在13中。

而实际上两者是没有区别的:

38 + 5 -> (3+1)+3

3+8+5 -> 3+(10+3) -> 3+1+3

你可能感兴趣的:(LeetCode)