LeetCode 258. Add Digits(数位相加)
2016-04-09 05:47
351 查看
原题网址:https://leetcode.com/problems/add-digits/
Given a non-negative integer
one digit.
For example:
Given
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.
方法一:通过模拟数位相加的过程(循环或者递归)计算结果。
方法二:通过数据样例分析找出规律。吓晕了,这是在提示下做出来的,可见分析简单数据样本找规律的重要性!
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
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.
方法一:通过模拟数位相加的过程(循环或者递归)计算结果。
public class Solution { public int addDigits(int num) { if (num < 10) return num; int sum = 0; while (num > 0) { sum += num % 10; num /= 10; } return addDigits(sum); } }
方法二:通过数据样例分析找出规律。吓晕了,这是在提示下做出来的,可见分析简单数据样本找规律的重要性!
public class Solution { public int addDigits(int num) { if (num == 0) return 0; return (num-1)%9+1; } }
相关文章推荐
- 斯坦福公开课:Statistical Learning中做错的选择题
- IBM SPSS Modeler 【6】 建立决策树
- IBM SPSS Modeler 【5】 关联分析
- IBM SPSS Modeler 【4】 神经网络模型的测试验证
- 文件权限与文件查询
- IBM SPSS Modeler 【3】 神经网络的生成
- IBM SPSS Modeler 【3】 Kohonen聚类分析和直接分析法
- scanf输入格式实验&printf语句输出实验
- IBM SPSS Modeler 【2】 两步聚类
- IBM SPSS Modeler 【1】 K均值聚类
- 键盘推动视图上下移效果
- 人生需要目标
- LeetCode 257. Binary Tree Paths
- c++解惑之读取文件getline
- [python之数据分析] 基础篇1- Numpy,Scipy,Matplotlib 快速入门攻略
- LeetCode 256. Paint House(房子涂色)
- Visio studio 2015 使用串口
- [Python极速入门] Python 2.7极速入门讲义
- android RelativeLayout属性和使用, 实现上面view叠加在下面view之上的效果2
- [转] Mac下 快速写博客的软件 MarsEdit