[LeetCode] Add Digits
2015-09-12 23:34
357 查看
Given a non-negative integer
For example:
Given
分析一:最简单的循环方法
分析二:参考https://leetcode.com/discuss/52122/accepted-time-space-line-solution-with-detail-explanations
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.
分析一:最简单的循环方法
class Solution { public: int addDigits(int num) { while (num / 10 != 0) { int temp = 0; while (num != 0) { temp += num % 10; num /= 10; } num = temp; } return num; } };
分析二:参考https://leetcode.com/discuss/52122/accepted-time-space-line-solution-with-detail-explanations
class Solution { public: int addDigits(int num) { return 1 + (num - 1) % 9; } };
相关文章推荐
- 自建CA
- 【CCF】最优配餐
- emberjs
- (一)初学用markdown编辑文字的几种常见语法
- jQuery学习之滑动
- 别忙,我先感觉一下自己
- Lecture1-4Components of ML
- android中用Spannable在TextView中设置超链接、颜色、字体
- codeforces 280 C Game on Tree (离散概率)
- java操作mongodb(聚合函数)-分组找出每组的最大值
- 用户等级触发器
- 第一百六十三天 how can I 坚持
- web前端之网站seo优化学习笔记
- 蔡勒公式求今天是星期几?
- (C++)string类杂记
- 矩阵基础算法实现
- Deep learning:四十四(Pylearn2中的Quick-start例子)
- Unity3D笔记第八天——音频处理
- 算法导论-分治策略
- hadoop集群基本配置