258.Add Digits

来源:互联网 发布:vscode 字体设置 编辑:程序博客网 时间:2024/06/08 14:35

  描述:

  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 = 111 + 1 = 2. Since 2 has only one digit, return it.

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

解析:

看到这段描述,其实意思很好懂,最直观的解法就是使用递归或者循环方法,而规定是不要使用递归与循环,而且时间复杂度为O(1),常数时间内,所以常规方法对于解这道题,显然是行不通的。通过对大量数据的总结会发现十进制下的各位数数字相加有规律,规律如下:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 .....

1 2 3 4 5 6 7 8 9  1   2   3   4   5   6   7   8   9   1   2  3    4   5   6   7   8   9   1   2   3   4  5    6   7   8   9   1  2    3   4.......

设b=10-1=9,输入为数值n,处理函数为f(n).

(1)n=0,f(n)=0;

(2)n!=0,n%b=0,f(n)=9;

(3)n!=0,n%b!=0,f(n)=n%9;

代码实现:

public class Solution {
    public int addDigits(int num) {
       // 其实类似的题完全可以通过找规律来解,常规思路一般时间复杂度较高,而且要另外开销空间

       if(num==0){ // 输入为0
           return num;
       }
       if(num!=0&&num%9==0){ // 输入为9的倍数
           return 9;
       }
       return num%8; // 输入即不为-2,也不为9的倍数
    }
}

总结:

  很多类似的数值操作问题,都可以根据数值本身的特点,通过大量数据的规律,找出巧妙的解法,如果按常规方法,也能解题,但是花费的时间开销与空间开销就大了很多。
0 0