【LeetCode OJ 258】Add Digits
2016-01-15 20:18
302 查看
题目链接:https://leetcode.com/problems/add-digits/
题目:Given a non-negative integer
repeatedly add all its digits until the result has only one digit.
For example:
Given
only one digit, return it.
解题思路:思路比较简单,就是求每个位的数之和,判断是否为小于10的数,是就返回结果,不是就继续做求每位数之和的操作。
示例代码:
题目: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
2has
only one digit, return it.
解题思路:思路比较简单,就是求每个位的数之和,判断是否为小于10的数,是就返回结果,不是就继续做求每位数之和的操作。
示例代码:
public class Solution { public int addDigits(int num) { int temp=addSum(num); if(temp<10) { return temp; } else return addDigits(temp); } /** * 求每位的数之和 * @param num * @return */ private int addSum(int num) { if(num<10) return num; int i=0; int sum=0; while(num!=0) { i=num%10; sum+=i; num=num/10; } return sum; } }
相关文章推荐
- Android 采用线程方法动态显示文字
- Tomcat剖析(五):Tomcat 容器
- Ubuntu14.04LTS上安装fcitx输入法
- 登录界面Linearlayout嵌套
- =="和Equals的区别
- python join字符连接函数的使用方法
- C#关于Clone()方法的介绍
- C++之路进阶——树链剖分/块状树(树的统计)
- Linux Is Not Matrix——keepalived安装
- ios基本图形绘制
- 建造者模式
- python的MySqldb使用
- 使用RandomAccessFile获取文件的MD5值
- javascript——四种函数调用形式
- Notepad++中代码格式化插件NppAStyle
- aawf
- 20160115--Hibernate
- 树链剖分 树的统计
- Java学习之finally关键字总结
- idea无法调试的解决方案。之一。