LeetCode 258 Add Digits(数字相加,数字根)
2024-09-06 14:55:02
翻译
给定一个非负整型数字,反复相加其全部的数字直到最后的结果仅仅有一位数。
比如:
给定sum = 38,这个过程就像是:3 + 8 = 11。1 + 1 = 2。由于2仅仅有一位数。所以返回它。
紧接着:
你能够不用循环或递归在O(1)时间内完毕它吗?
原文
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?
分析
事实上我并不会写,循环和递归都不能用……我还能怎么办呐。
然后看了LeetCode上给的提示。看了维基百科的一篇文章:Digital root。
有了这个的话,就非常easy了。详细这个公式的细节,大家自己參看维基吧,由于篇幅过长就不翻译了。
代码
class Solution {
public:
int floor(int x) {
return (x - 1) / 9;
}
int addDigits(int num) {
return num - 9 * floor(num);
}
};
最新文章
- *HDU1847 博弈
- 爱与恨的抉择:ASP.NET 5+EntityFramework 7
- job history 的查看
- CSS3动画:YouTube的红色激光进度条
- android 利用Path.cubicTo 画 贝塞尔曲线
- C++从键盘输入文件结束符
- 创建ubuntu软件源
- easyui tree 模仿ztree 使用扁平化加载json
- Html.ActionLink 几种重载方式说明及例子
- gulp使用流程
- 数据结构中,几种树的结构表示方法(C语言实现)
- http协议、模块、express框架以及路由器、中间件和mysql模块
- 【PAT】B1004 成绩排名
- Android Studio提示 Connection reset
- flume 架构设计优化
- [PowerShell Utils] Remotely install Hyper-V and Failover Cluster feature on a list of windows 2012 servers
- PowerShell 获取Site Collection下被签出的文件
- maven用变量的方法统一管理jar包版本
- 项目管理PV、EV、AC、BAC、EAC、ETC等计算
- [转]Spring事务<;tx:annotation-driven/>;