Question:
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?
Analysis:
问题描述:给出一个非负的证书,重复把他的各位数加起来直至最后为个位数。
思考:你能够不用循环而在O(1)的时间内完成这道题目嘛?
思路一:模仿题目运算的过程,当加起来不是个位数时就把每一位都相加。
思路二:如果不用循环,没有想到思路啊。。参考了网络上得答案后有所启发,返回的数肯定都在0-9之间,因此找到他们的规律即可。
Answer:
思路一:
public class Solution { public int addDigits(int num) { while(num >= 10){ ArrayList<Integer> l = new ArrayList<Integer>(); while(num/10 != 0) { l.add(num%10); num = num/10; } l.add(num); num = 0; for(int i=l.size()-1; i>=0; i--) { num += l.get(i); } } return num; } }
思路二:
public class Solution { public int addDigits(int num) { if(num < 10) return num; return (num - 1)% 9 + 1; } }