LeetCode258 Add Digits

来源:互联网 发布:数据库营销 编辑:程序博客网 时间:2024/06/05 12:21

不废话:

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.

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

Hint:

  1. A naive implementation of the above process is trivial. Could you come up with other methods?
  2. What are all the possible results?
  3. How do they occur, periodically or randomly?
  4. You may find this Wikipedia article useful.
class Solution {public:    int addDigits(int num) {        if(num==0){return 0;}        return ((num-1)%9+1);    }};

重点和技巧是上面的(num-1)%9+1

关于数论,有下面技巧:

ab=a*10+b;

ab%9=(a*9+a+b)%9=(a+b)%9

同理之下:

abc=a*100+b*10+c

abc=(a*99+b*9+a+b+c)%9=(a+b+c)%9

(自然数mod(9)后是0~8,而当需要输出1~9时,可以先mod(9)再整体+1)

0 0
原创粉丝点击