LeetCode-258 Add Digits
来源:互联网 发布:倒班表软件 编辑:程序博客网 时间:2024/06/06 11:49
https://leetcode.com/problems/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?
1、知识点:Digital Root(数根)
一个数的数根等于它对9取模;特殊情况:该数为9的倍数时,其数根为9。
https://en.wikipedia.org/wiki/Digital_root
http://baike.baidu.com/link?url=1-CBAkwvBe4Qd1elJ-6ILT2pE9bX4DZzjvKRMNi1137G4_1Pf66Jxlp-O8r-GORul4EsfxEdV_GdNbI13aoUkK
2、(12ms)
class Solution {
public:int addDigits(int num) {
if(num==0)
return 0;
return (num%9==0)?9:num%9;
}
};
3、(8ms)
class Solution {
public:
int addDigits(int num) {
if(num==0)
return 0;
if(num%9==0)
return 9;
return num%9;
}
};
4、(8ms)
class Solution {
public:
int addDigits(int num) {
return (num-1)%9+1; // 其中,%运算的结果符号与被除数符号一致,故 -1%9 = -1
}
};
- 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
- 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经典解法
- python多重继承 MRO
- java多线程:循环输出ABC
- 深入理解java范型
- Swift UIButton、UILabel、UITextField的创建与用法
- LeetCode-258 Add Digits
- Android开发笔记之音乐播放器
- java缓存ehcache和memcache区别
- STL之list容器详解
- java compiler level does not match解决方法
- 剑指offer27--查找数组中最小的k个数
- 26. Remove Duplicates from Sorted Array
- UML系列图--用例图
- Azkaban Getting Started