258. Add Digits
2016-02-23 20:26
357 查看
题目:
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?
思路:
乍一看确实没有思路,但是后来在看了discuss之后明白了这又是一个找规律的问题。
代码如下:
public class Solution {
public int addDigits(int num) {
if(num == 0){
return 0;
}
int mynum = num % 9;
if(mynum == 0){
mynum = 9;
}
return mynum;
}
}
需要注意的是需要将模数得到的0值改成9.
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?
思路:
乍一看确实没有思路,但是后来在看了discuss之后明白了这又是一个找规律的问题。
代码如下:
public class Solution {
public int addDigits(int num) {
if(num == 0){
return 0;
}
int mynum = num % 9;
if(mynum == 0){
mynum = 9;
}
return mynum;
}
}
需要注意的是需要将模数得到的0值改成9.
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树