[leetCode]Add Digits
2016-01-13 19:31
267 查看
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.
题意: 依次将数的每一位相加(①),若结果不为个位数,则再次执行第一步,直到结果为个位数.
思路:这道题思路简单
还有更简单的方法,如下,只是我还没想明白为何.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
题意: 依次将数的每一位相加(①),若结果不为个位数,则再次执行第一步,直到结果为个位数.
思路:这道题思路简单
int addDigits(int num) { int addNum = 0; while( 0 != num ) { addNum += num%10; addNum = addNum%10 + addNum/10; num /= 10; } return addNum; }
还有更简单的方法,如下,只是我还没想明白为何.
int addDigits(int num) { return (num - 1)%9 + 1; }
相关文章推荐
- 扣丁学堂——Loader
- DbVisualizer报错You have an error in your SQL syntax; check the manual that corresponds to your MySQL
- hadoop2.6.0版本集群环境搭建
- android异步加载图片并缓存到本地实现方法
- iOS --NSPredicate
- LightOJ1033 Generating Palindromes(区间DP/LCS)
- AjaxAnywhere+struts用法
- Java 数组
- Lua 类型和值
- 网页手机宽度
- HDOJ 2091 空心三角形
- click through rate prediction
- New Relic for Java
- Micheal Nielsen's神经网络学习之二
- Disk Space Usage : unallocated, unused and reserved
- myeclipse使用常见问题
- 【Python】Python中中文的字符串格式化对齐
- 程序包javax.servlet.annotation不存在
- JAVA中三种URL连接方法
- BZOJ 1600: [Usaco2008 Oct]建造栅栏|动态规划