LeetCode——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?
题意很简单,最容易想到的办法就是循环迭代,如果是<10的就返回。下面是一种递归的方法。
public class Solution { public int addDigits(int num) { if(num < 10) { return num; } //1023 int t = 0; while(num >= 1) { t += num % 10; num = num / 10; } return addDigits(t); } }
那么怎么做才能不用递归和循环迭代来把复杂度降到O(1)呢,这让我联想到了公式。来通过数据找找规律。
前30个数据测试:
public static void main(String[] args) { for(int i=0; i<30; i++) { System.out.println(i + " " + addDigits(i)); } }
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 1
11 2
12 3
13 4
14 5
15 6
16 7
17 8
18 9
19 1
20 2
21 3
22 4
23 5
24 6
25 7
26 8
27 9
28 1
29 2
找出来规律了吧。
其实是这样的:(num-1) % 9 + 1
public class Solution { public int addDigits(int num) { return (num-1) % 9 + 1; } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112835275-168981902.gif)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112841431-2047172832.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112847494-1544911856.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112904385-918783221.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111120143119-1302805212.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112856369-1466718103.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112830416-794416355.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111113919510-1155220901.gif)