<LeetCode>258. Add Digits
2016-03-21 12:26
459 查看
258. Add Digits
Total Accepted:79895 Total Submissions:
165648 Difficulty: Easy
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.
一般的想法就是把每个数的个位,十位都分开,再一次次算:
class Solution { public: int addDigits(int num) { int i=0, x=2; while(x>1) { i=0; x=0; while(num) { i+=num%10; num=num/10; x++; } if(x == 1) break; num =i; } return i; } };
还可用递归:
class Solution { public: int addDigits(int num) { int sum=0; while(num){ sum=sum+num%10; num=num/10; } if(sum<10){ return sum; } else{ return addDigits(sum); } } };
相关文章推荐
- C++ delete指针二次程序崩溃
- iOS之了解沙盒
- 逆向某停车app(原创)
- 《JS高程》对象&原型学习笔记
- jvm:停止复制、标记清除、标记整理算法(垃圾回收)
- 【C++】《C++标准程序库》小结第十章-特殊容器
- 使用变量分组的sql : 排序后再分组,取分组的第一个
- 交换排序---快速排序
- NFS的安装、配置与使用
- Android 6.0 HttpClient弃用问题
- tcp/ip ---链路层
- Java学习第一步——JDK安装及Java环境变量配置
- 从2月14号开始,上传AppStore会碰到:Failed to locate or generate matching signing assets
- appium定位元素java篇
- 编译vlc android arm64-v8a
- 快速排序C++
- 第三周学习进度表
- 设计模式之1--五大原则
- 欢迎使用CSDN-markdown编辑器
- 在ubuntu上搭建svn服务器