翻译

给定一个非负整型数字,反复相加其全部的数字直到最后的结果仅仅有一位数。

比如:

给定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);
}
};

最新文章

  1. *HDU1847 博弈
  2. 爱与恨的抉择:ASP.NET 5+EntityFramework 7
  3. job history 的查看
  4. CSS3动画:YouTube的红色激光进度条
  5. android 利用Path.cubicTo 画 贝塞尔曲线
  6. C++从键盘输入文件结束符
  7. 创建ubuntu软件源
  8. easyui tree 模仿ztree 使用扁平化加载json
  9. Html.ActionLink 几种重载方式说明及例子
  10. gulp使用流程
  11. 数据结构中,几种树的结构表示方法(C语言实现)
  12. http协议、模块、express框架以及路由器、中间件和mysql模块
  13. 【PAT】B1004 成绩排名
  14. Android Studio提示 Connection reset
  15. flume 架构设计优化
  16. [PowerShell Utils] Remotely install Hyper-V and Failover Cluster feature on a list of windows 2012 servers
  17. PowerShell 获取Site Collection下被签出的文件
  18. maven用变量的方法统一管理jar包版本
  19. 项目管理PV、EV、AC、BAC、EAC、ETC等计算
  20. [转]Spring事务<tx:annotation-driven/>

热门文章

  1. 用DOM动态控制表格
  2. html5播放m3u8视频,web端看直播
  3. Nginx-虚拟主机配置问题
  4. C++笔试专题一:运算符重载
  5. python(2) 图像通道,几何变换,裁剪
  6. php异常处理的深入
  7. h5调用底层接口的一些知识
  8. Linux下的ioctl()函数详解
  9. 【Codeforces Round #420 (Div. 2) A】Okabe and Future Gadget Laboratory
  10. View 和 ViewGroup 的 hasFocusable