渣渣写LEETCODE——258. Add Digits
2016-05-06 21:03
344 查看
Problem:
Given a non-negative integer
For example:
Given
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Solution:
用模10取出个位,用除10丢掉个位。
O(1)的解法想出来再补充。
Code:
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?
Solution:
用模10取出个位,用除10丢掉个位。
O(1)的解法想出来再补充。
Code:
/*__xz__*/ class Solution { public: int addDigits(int num) { int result = 0; if (num < 10) return num; else { while (num != 0) { result += num%10; num /= 10; } } return result; } };
相关文章推荐
- C++基础知识——二维数组做函数参数
- INotifyPropertyChanged接口
- 道德经--老子
- Dubbo源码分析(四):dubbo中bean的加载
- uva10635(LCS转换为求LIS)
- [svc][op]SSH公钥认证+优化
- Java 8从永久代到metaspace
- Common used English
- HDU 专题分类
- shell---消除文件后缀四种方法
- Object Detection with DPM
- nyoj55懒省事的小明(STL优先队列)
- 本文建模系列值三:LDA感悟
- poj 1321棋盘问题(补充)
- IOS自动释放原理及详解
- C经典 结构图初始化三种方式
- 文本建模系列之二:pLSA
- MAC OS X 系统怎么样?
- java底层知识(5)--递归与尾递归总结
- 文本建模系列之一:LSA