leetcode 258: Add Digits
2015-09-14 16:38
393 查看
题目:
Given a non-negative integernum, 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?
Hint:
A naive implementation of the above process is trivial. Could you come up with other methods?
What are all the possible results?
How do they occur, periodically or randomly?
You may find this Wikipedia article useful
思路:
不用循环或者递归的时候,没有做出来;提示没看懂,也没有认真思考;编码1:
public class Solution { public int addDigits(int num) { int sum = 0; while(true) { sum += num%10; num = num/10; if(num == 0) { if(sum < 10) break; else { num = sum; sum = 0; } } } return sum; } }
编码2:
针对follow up,一共有多少种结果?1-9;每种结果是随机的还是有规律的?(注释:代码为粘贴copy其他人的)public class Solution { public int addDigits(int num) { return 1 + (num-1) % 9; } }
相关文章推荐
- win10无法连接网络怎么办?Win10提示无法连接此网络的原因与解决方案
- 接口是否可继承接口? 抽象类是否可实现(implements)接口? 抽象类是否可继承实体类
- 接口是否可继承接口? 抽象类是否可实现(implements)接口? 抽象类是否可继承实体类
- 接口是否可继承接口? 抽象类是否可实现(implements)接口? 抽象类是否可继承实体类
- 接口是否可继承接口? 抽象类是否可实现(implements)接口? 抽象类是否可继承实体类
- redis3.0集群部署方案
- KMP的实现
- Linux下创建用户组及用户
- 数据库删除重复记录的sql
- hdu5438Ponds
- CocoaPods的详解及安装使用
- SQL 标量函数-----日期函数datediff()、 day() 、month()、year()
- IOS网络第四天 -网络文件上传(0923略)
- 如何在Win8侧边栏显示工具项?Win8侧边栏显示工具项的方法
- 第2周项目3体验复杂度
- Crazyflie2.0飞行器参考网站
- 项目2 - 建设“顺序表”算法库
- Developer-Handler
- nginx 内置变量大全
- Linux 管道