LeetCode[258]——Add Digits

来源:互联网 发布:.json打开 编辑:程序博客网 时间:2024/06/05 20:04

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 = 111 + 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 int addDigits(int num) {        while(num>=10){            num = (num/10)+num%10;        }        return num;    }
解法二:

题目要求没有递归,没有循环,且时间复杂度为O(1)。那就找规律

前30个数据测试:  

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

找出来规律了吧。

其实是这样的:

<pre name="code" class="java">public class Solution {public int addDigits(int num) {       return 1 + (num-1)%9;     }} 


0 0
原创粉丝点击