[LeetCode] 258. Add Digits

原题链接: https://leetcode.com/problems/add-digits/

1. 题目介绍

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

给出一个非负数num,将num的每一位相加,得到一个新的数,再将这个新的数的每一位相加,重复这样的操作,直到得到的数只有个位时停下来。
返回这个个位数。

建议:不使用任何循环和递归来实现,时间复杂度为O(1)

Example:

Input: 38
Output: 2 
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 
             Since 2 has only one digit, return it.

2. 解题思路

2.1 循环或者递归

虽然说题目不提倡用循环或者递归的方法,但是我还是写了一下,简单看一看即可。
实现代码:循环

class Solution {
    public int addDigits(int num) {
        
		int ans = num;
		while(ans>=10) {
			int b = 0;
	        while(ans > 0) {
	        	b += ans%10;
	        	ans = ans/10;
	        }
	        ans = b;
		}
		return ans;
    }
}

实现代码:递归

class Solution {
    public int addDigits(int num) {
        
		int ans = num;
		while(ans>=10) {
			ans = FindDigitsSum(ans);
		}
		return ans;
    }
	
	public int FindDigitsSum(int nums) {
		int a = nums;
		int b = 0;
        
		while(a > 0) {
        	b += a%10;
        	a = a/10;
        }
		return b;
	}
}

2.2 找规律

如果不用递归,不用循环,且时间复杂度为O(1)。这极有可能有一些数学规律。
于是打印一下0-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
30 3

可以发现,除了0以外,结果从1到9不停地在循环。于是答案就非常清晰了

实现代码

class Solution {
    public int addDigits(int num) {
        return (num%9 == 0 ? (num==0 ? 0 : 9) : num%9 );
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值