Easy-21

来源:互联网 发布:淘宝上的零食安全吗 编辑:程序博客网 时间:2024/06/01 08:06

leetcode   258. Add Digits           

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?


AC:

int addDigits(int num) {
    return 1+(num-1)%9;
}


tips:刚开始看到这个题目,首先想到的就是循环一次就行了,但是题目要求O(1)的复杂度,所以......然后就开始了百思不得其姐。

一个个列出来看看有没有什么规律。。 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20.。。。。

结果应该是 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 .。。。。

模9?!然后就可以开始coding 了 ....

0 0
原创粉丝点击