题目:

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 2 has
only one digit, return it.

Follow up:

Could you do it without any loop/recursion in O(1) runtime?

Hint:

  1. A naive implementation of the above process is trivial. Could you come up with other methods?

  2. What are all the possible results?
  3. 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;
}
};

最新文章

  1. SDC Tcl package of Timequest
  2. ios10 UNNtificationRequest UNUserNotificationCenter的应用 推送之本地推送
  3. PHP基础班初学心得:关于网页创作
  4. C预处理和C库
  5. java环境
  6. sublimeCodeIntel 的配置
  7. 迭代输出Map和List<Map<String,Object>>的方法
  8. Bootstrap_CSS全局样式
  9. 从wordcount 开始 mapreduce (C++\hadoop streaming模式)
  10. grep参数说明及常用用法
  11. YouTube CEO关于工作和生活平衡的完美回答
  12. zhihu spark集群,书籍,论文
  13. thinkphp中的where()方法
  14. poj 2406 Power Strings(KMP变形)
  15. 决策树ID3算法
  16. AtCoder Beginner Contest 069【A,水,B,水,C,数学,D,暴力】
  17. 【数据库】mysql数据库索引
  18. 04_ switch 练习 _ 你及格了吗
  19. 为什么C++11引入了std::ref?
  20. Unity 敌人波次设计

热门文章

  1. php安装redis扩展 windows
  2. maven这些工具负责创建项目,然后maven负责打包好war包扔进tomcat容器,tomcat容器接受的只是jar包
  3. android canvas 画图笔记
  4. PCA(Principal Components Analysis)主成分分析
  5. I hate it (线段树)
  6. POJ 2318 叉积判断点与直线位置
  7. linux 数据库
  8. 【转】Android 服务器之SFTP服务器上传下载功能 -- 不错
  9. cookie、sessionStorage和localStorage
  10. SAS拆分数据集