LeetCode Algorithms #258 <Add Digits>
2015-10-07 08:02
405 查看
Given a non-negative integer
repeatedly add all its digits until the result has only one digit.
For example:
Given
only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
思路:
非零整数,每增加1,
1.如果个位是0~8,则是个位数加1,十位百位等都不会改变。
则会导致各个数位加和的结果加1。
2.如果个位数是9,个位加1变0,十位加1。
则会导致各个数位加和的结果减9加1。
这个规律在每一次加和这个数的各个数位时都有效,所以最终一定是一个以9为最小周期变化的结果。
验证代码:
输出结果:
综上,解:
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
2has
only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
思路:
非零整数,每增加1,
1.如果个位是0~8,则是个位数加1,十位百位等都不会改变。
则会导致各个数位加和的结果加1。
2.如果个位数是9,个位加1变0,十位加1。
则会导致各个数位加和的结果减9加1。
这个规律在每一次加和这个数的各个数位时都有效,所以最终一定是一个以9为最小周期变化的结果。
验证代码:
#include <iostream> int main(int argc, const char * argv[]) { std::cout << "GoodMorning, Neuwyt!\n"; for(int idx = 1; idx < 100; idx++) { int tempResult = 0; tempResult = idx%10 + idx/10; if(tempResult/10) { tempResult = tempResult%10 + tempResult/10; } printf("%d, ", tempResult); } return 0; }
输出结果:
GoodMorning, Neuwyt! 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9,发现规律。
综上,解:
class Solution { public: int addDigits(int num) { int result = 0; result = 1 + (num-1)%9; return result; } };另:使用临时变量会导致解题的速度慢上几毫秒,但实际工作中更利于维护和阅读,本人工作的项目一般不太看重效率,也不是acm出身的,因此养成了这样写代码的习惯。
相关文章推荐
- django 中的ajax
- CF_#322(Div.2) D. Three Logos(greedy)
- 10.6上课——problem1切割木板(USACO 2006 November Gold)
- EGOTableViewPullRefresh 使用
- ubuntu14.04下安装indigo版ROS
- go语言 新手学习笔记 go基础教程
- go语言 类型:基础类型和复合类型
- go语言 匿名变量
- GO 学习笔记(三) 指针
- GOF设计模式(Design Patterns)
- 学科综合 | 当你在浏览器中输入Google.com并且按下回车之后发生了什么?
- google使用小技巧
- go语言编辑器:liteide
- golang 获取exe、dll、apk 版本号
- go语言 安装版 Windows7安装截图
- go语言最新版本 下载地址
- Using DAVID for GO and pathway enrichment analysi
- UVa 11292.Dragon of Loowater【贪心】【10月6】
- OC第七讲(Category类目)
- Go语言学习笔记一(语法篇)