(easy)LeetCode 258.Add Digits
2015-08-19 16:31
330 查看
Given a non-negative integer
For example:
Given
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
方法1:常规做法,循环,不符合题意。
方法2:找到规律,一行代码
代码如下:
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
2has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
方法1:常规做法,循环,不符合题意。
public class Solution { public int addDigits(int num) { while(num>9){ int p=0; while(num!=0){ p+=num%10; num=num/10; } num=p; } return num; } }
方法2:找到规律,一行代码
代码如下:
public class Solution { public int addDigits(int num) { return (num-1)%9+1; } }
相关文章推荐
- 数据库设计三大范式
- 桌面支持--重置skype密码链接
- The method replace(int, Fragment) in the type FragmentTransaction is not applica
- 回归-用极大似然估计来解释最小二乘
- Android Studio 快捷键
- C/C++经典源代码网站
- 几个基础数位DP (hdu 2089,hdu 3555 ,uestc 1307 windy 数)
- hdu 1599 floyed最短路
- OSGI
- 桌面支持--skype登陆不上
- JS文字球状放大效果代码分享
- LeetCode刷题小记---Reverse Integer
- createjs初学-关于getBounds和getTransformedBounds
- [置顶] LINUX新手常用命令[长期更新]
- 13Lync2013升级到SkypeForBusiness2015--迁移CMS&会议目录&呼叫允许控制
- [leetcode] 264.Ugly Number II
- iOS中级(一) 正则表达式
- 比较全面的JS验证
- HDU 2594 — Simpsons’ Hidden Talents
- 多重背包 (n种物品,每种m个)