[leetcode][math] Add Digits
2024-08-27 15:53:23
题目:
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 = 111 + 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:
- 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;
}
};
最新文章
- SDC Tcl package of Timequest
- ios10 UNNtificationRequest UNUserNotificationCenter的应用 推送之本地推送
- PHP基础班初学心得:关于网页创作
- C预处理和C库
- java环境
- sublimeCodeIntel 的配置
- 迭代输出Map和List<;Map<;String,Object>;>;的方法
- Bootstrap_CSS全局样式
- 从wordcount 开始 mapreduce (C++\hadoop streaming模式)
- grep参数说明及常用用法
- YouTube CEO关于工作和生活平衡的完美回答
- zhihu spark集群,书籍,论文
- thinkphp中的where()方法
- poj 2406 Power Strings(KMP变形)
- 决策树ID3算法
- AtCoder Beginner Contest 069【A,水,B,水,C,数学,D,暴力】
- 【数据库】mysql数据库索引
- 04_ switch 练习 _ 你及格了吗
- 为什么C++11引入了std::ref?
- Unity 敌人波次设计