leetCode题解:AddDigits
来源:互联网 发布:java返回值类型是类名 编辑:程序博客网 时间:2024/05/17 11:05
题意:
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
思路:
在后续的要求,要求我们不使用任何循环或递归手段,使得计算过程的开销是O(1)
这里我们要找出数学的联系,我们发现当输入的数字可以被9整除时,最后addDigit的结果是9(0除外),其余的结果就是num%9的值
这里输入的数字是非负,根据oj的测试,当输入数字是负数时,返回本身。
代码(java):
public int addDigits(int num) {
if(num<=0) return num;
if(num!=0&&num%9==0) return 9;
return num%9;
}
0 0
- leetCode题解:AddDigits
- LeetCode AddDigits
- addDigits
- 258AddDigits
- leetcode题解
- leetcode题解
- LeetCode 题解
- leetCode题解
- leetcode题解
- leetcode题解
- leetcode题解
- LeetCode题解
- LeetCode题解
- Leetcode题解
- Leetcode题解
- Leetcode题解
- Leetcode题解
- Leetcode题解
- POJ 1753 Flip Game(搜索+位运算)
- hdoj 1427 速算24点【经典dfs】
- Hive分析窗口函数之NTILE,ROW_NUMBER,RANK和DENSE_RANK
- (九)mybatis学习之缓存
- 商品内容页上传图片失败
- leetCode题解:AddDigits
- 安卓应用程序的签名
- 构造大数据时代国家安全战略
- hibernate 4 映射有序集合 sortedSet sortedMap
- spring mvc 预习
- 父亲给三个儿子分田(水题,但比较麻烦)
- win7 64 安装mysql-python
- 位运算符
- 在js中模拟Java中的Map