[leetcode][math] Add Digits
2015-08-16 14:31
363 查看
题目:
Given a non-negative integer
result has only 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?
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?
class Solution { public: int addDigits(int num) { int res = 0; bool doneFlag = false; while(1){ res = 0; while(num > 0){ res += num%10; num /= 10; } if(res/10 == 0) break; num = res; } return res; } };
class Solution { public: int addDigits(int num) { if(num == 0) return 0; if(num % 9 == 0) return 9; return num%9; } };
相关文章推荐
- 黑客专属记事本(编程记事本)
- hdu 5392 Infoplane in Tina Town (质因子分解求最小公倍数)
- android 控件中layout_width,layout_height与onMeasure(int widthMeasureSpec, int heightMeasureSpec)
- 黑马程序员——C语言笔记之if,if....else....,switch判断
- POJ 1001 Exponentiation 求高精度幂
- CodeForces-552A - Vanya and Table
- 关于time的使用
- 2015年面试准备(1)-----c/c++的区别
- 认识javascript范围和作用域链
- HDU_1847 Good Luck in CET-4 Everybody!(SG函数)
- 制作自己的第一个报表
- 编写高质量代码改善C#程序的157个建议——建议48:Dispose方法应允许被多次调用
- Tarena - Week01:猜字母
- 关于读取速度
- HDOJ-5391 Zball in Tina Town(数学)
- 为什么图片加载我首先Glide
- Java中的八种基本数据类型所占字节的求法
- 基于bind工具实现DNS子域授权、子域父域相互解析
- Spring依赖注入
- 110 Balanced Binary Tree