LeetCode-258. Add Digits
来源:互联网 发布:力高答题软件 编辑:程序博客网 时间:2024/06/07 12:58
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?
-----------------------------------------------------------------------------------------------------------------------
这道题最简单的思路是用循环,但是题目要求不能用,所以需要另寻它法。
对num展开 38=3*10+8 ,那么它的数字根就是 3+8。 对num变形 38=3*10+8 ==> 38=(3+8)+3*9。
那么为了求数字根,可以对num进行模9 : 38%9 = (3+8)%9+0。
考虑到如果数字根为9时求模后会等于0,则首先对num减1再求模,然后在加1。
则38的数字根 (38-1)%9+1 = 2.
代码如下:
public class Solution { public int addDigits(int num) { return 1 + (num-1)%9; }}
阅读全文
0 0
- 【LeetCode】258.Add Digits
- LeetCode 258. Add Digits
- LeetCode : 258. Add Digits
- leetCode 258. Add Digits
- LeetCode 258. Add Digits
- 258. Add Digits LeetCode
- LeetCode 258. Add Digits
- LeetCode 258. Add Digits
- leetcode 258. Add Digits
- [LeetCode]258. Add Digits
- LeetCode 258. Add Digits
- <LeetCode>258. Add Digits
- leetcode--258. Add Digits
- LeetCode 258. Add Digits
- LeetCode *** 258. Add Digits
- Leetcode 258. Add Digits
- 258.[LeetCode]Add Digits
- 【leetcode】258. Add Digits
- 【算法】常用排序算法时间空间复杂度
- MySQL最大连接数设置
- 概率图模型9:贝叶斯网络
- 双向链表删除问题
- redirect
- LeetCode-258. Add Digits
- ThreadPoolExecutor使用介绍
- 深度学习-微调
- 14、权限管理之文件特殊权限SUID、SGID、SBIT
- ueditor插件在ie上传图片出现下载JSON文件的解决
- cocos2d-x 3.3连接Xcode9编译时报错:call to unavailable function system not available on ios
- Android 中性能优化工具之Hierarchy Viewer使用总结
- cf -148 b double追赶问题模拟
- PAT(B)_1043. 输出PATest(20)