LeetCode 258: Add Digits 题解
来源:互联网 发布:上古世纪捏脸数据在那 编辑:程序博客网 时间:2024/05/21 17:45
刚开始以为是一道水题,一下就过了,结果题没看完,要求时间复杂度为
LeetCode 258: Add Digits
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?
用循环或者递归的话在思想上很简单,下面是水过的代码:
int addDigits(int num) { while(num >= 10){ int temp_sum = 0; while(num > 0){ temp_sum += num % 10; num /= 10; } num = temp_sum; } return num;}
下面来看看怎么不用循环或者递归来解这道题。
解法1:
这道题其实是有规律的:
答案就是对9取余,但是9的倍数取余为0,所以要处理特殊情况:
int addDigits(int num) { return (num != 0 && 0 == num % 9) ? 9 : num % 9;}
解法2:
下面的例子引用自该题的discussion
首先需要知道:
10^k % 9 = 1
a*10^k % 9 = a % 9
假如有一个数字 x = 23456
x = 2* 10000 + 3 * 1000 + 4 * 100 + 5 * 10 + 6
2 * 10000 % 9 = 2 % 9
3 * 1000 % 9 = 3 % 9
4 * 100 % 9 = 4 % 9
5 * 10 % 9 = 5 % 9
那么x % 9 = ( 2+ 3 + 4 + 5 + 6) % 9, 注意 x = 2* 10000 + 3 * 1000 + 4 * 100 + 5 * 10 + 6
所以有: 23456 % 9 = (2 + 3 + 4 + 5 + 6) % 9
所以解法就是取各位数相加,然后对9取余,其实和第一种解法本质上是相同的,同样需要9的倍数需要特殊处理。
- LeetCode 258: Add Digits 题解
- LeetCode题解:Add Digits
- LeetCode 题解(182): Add Digits
- Leetcode题解 258. Add Digits
- LeetCode 258. Add Digits 题解
- 【Leetcode题解】258.Add Digits
- leetcode 258: Add Digits
- 258Add Digits - LeetCode
- leetCode #258 Add Digits
- [LeetCode 258] Add Digits
- LeetCode(258)Add Digits
- leetcode-258-Add Digits
- [leetcode 258]Add Digits
- [Leetcode]#258 Add Digits
- LeetCode 258----Add Digits
- LeetCode 258 : Add Digits
- 【LeetCode】258 Add Digits
- Leetcode - 258 - Add Digits
- SQL Server中多对多关系的实现
- 自定义View实现带边框的进度条
- 迈思德物联网网关极简宣传页
- hdu5861 Road(线段树成段更新+优先队)
- SDUT2139图结构练习——BFS——从起始点到目标点的最短步数
- LeetCode 258: Add Digits 题解
- 50. Pow(x, n)
- sdut oj2143 图结构练习——最短路径
- ASCII码转换
- 在IntelliJ IDEA中使用JUnit5
- 给WebView添加漂亮的加载进度条
- 机器学习&数据挖掘笔记_16(常见面试之机器学习算法思想简单梳理)
- poj 3468 A Simple Problem with Integers
- HDU 5696 区间的价值