LeetCode 258 Add Digits(技巧 || 递归)

来源:互联网 发布:在线室内设计软件 编辑:程序博客网 时间:2024/06/07 03:23

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?

题目大意:给出一个非负整数num,重复相加它的每一位直到最后只剩1位。

解题思路1:利用递归解决问题。

代码如下:

int addDigits(int num) {    return num/10 ? addDigits(num%10+addDigits(num/10)) : num;}

解题思路2:利用公式dr(n) = 1 + ((n - 1) mod 9)可以在O(1)时间内求解,详解见digital root

代码如下:

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

0 0
原创粉丝点击