第四周LeetCode
来源:互联网 发布:知乎 武侠 编辑:程序博客网 时间:2024/06/17 01:00
题目 Easy
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?
实现思路
将数字转成string类型,每次读取字符串的一位,转成int类型后,然后加起来,再把和转化成string类型,直到和转成string类型后长度小于2.该算法的复杂度为O(k),k为num的位数。
实现代码
int addDigits(int num) { //用于把int转成string stringstream ss; ss << num; string str = ss.str(); //sum记录每个位数相加得到的结果 int sum = num; //当sum为1位时返回 while (str.length() > 1) { sum = 0; stringstream s2; for (int i = 0; i < str.length(); i++) { stringstream s1; int temp; s1 << str[i]; s1 >> temp; sum += temp; } s2 << sum; s2 >> str; } return sum; }
ps:后来又去看了一下别人的算法,这个问题其实就是求数根(Digital root),维基百科上的文章有讲解树根的规律(https://en.wikipedia.org/wiki/Digital_root)。
1到9的树根为1-9,
10-18的树根为1-9,
19-27的树根为1-9,
…
…
由此可以出树根每9个就循环一次,因此可以得出公式
或,
因此该实现代码可以简化为一行:
int addDigits(int num) { return 1+((n-1)% 9));}
算法复杂度为O(1).
阅读全文
0 0
- leetcode-python 第四周
- leetcode-第四周
- 第四周leetcode题
- [leetcode] 第四周作业
- LeetCode题解 第四周
- 第四周LeetCode
- leetcode第四周解题报告
- LeetCode 算法习题 第四周
- LeetCode 算法习题 第四周
- 第四周LeetCode算法题两道
- 第四周:[leetcode] 126. Word Ladder II
- leetcode【第四周】 交换节点对
- 第四周:[Leetcode]207. Course Schedule
- 第四周:[Leetcode]210. Course Schedule II
- 第四周:[LeetCode]332. Reconstruct Itinerary
- 第四周
- 第四周
- 第四周
- HDU 3394 Railway 点双连通分量
- linux学习笔记
- sqli-labs学习记录(三)
- iOS 快捷键~窗体、帮助
- java反射机制优缺点
- 第四周LeetCode
- 反射-动态代理设计模式
- bzoj1967: [Ahoi2005]CROSS 穿越磁场
- Win7/Win10环境安装:Cuda+keras+tensorflow-gpu
- Java代码优化实现
- Spring 源码框架搭建
- MIT的博士后,国庆用特斯拉无人车娶媳妇
- 母函数
- spring mvc 和ajax异步交互完整实例代码