题目原址
https://leetcode.com/problems/add-digits/description/
题目描述
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代码,还有自己找了几个例子实验之后,发现,只要将给定的数按照三个条件进行划分即可
- 如果给定的数本身就是一个一位数,则直接返回
- 如果给定的数本身不是一个一位数,但是是9的整数倍数,则直接返回9,因为从输入的数是18的例子可以看出,
18 = 1 + 8 = 9
所以返回的结果是9,如果给定的数是19,则19 = 1 + 9 = 10
10 = 1 + 0 = 1
,所以19 返回的是1,因为19 %9 = 1,从这两个例子可以看出,如果不是9的倍数,则返回num%9即可
解决该题的关键就是找几个例子然后分析判断条件即可
AC代码
class Solution {
public int addDigits(int num) {
if(num < 10)
return num;
else if(num %9 == 0)
return 9;
else
return num %9;
}
}