Question 258:
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
中文解释: 对于一个非负的整数n, 把其每位数的数字相加求和,直到其和小于10.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
算法这里提供两种思路:
1)不断遍历求和直到小于10
这是一种比较直观的想法,只需要不断的求和就行了,下面给出代码:
/**
* 这个是最普通的算法,不停循环求出每位的和.
* @By 娄宇庭
* @param num
* @return
*/
public static int addDigits(int num) {
if(num<10)
return num;
int result = num;
while (result>=10){
int temp = 0;
//将待求的多位数先转换成字符串再转换成字符数组;
char[] numStrs = new Integer(result).toString().toCharArray();
//遍历字符数组,获取每个字符数组代表的数,然后相加
for(int i=0; i<numStrs.length; i++){
temp += Integer.valueOf(String.valueOf(numStrs[i]));
}
result = temp;
}
return result;
}
2)利用取余的特性求解:
example: 比如438
438 == 40*10 + 3*10 +8
4+3+8 == 4*(10%9)(10%9) + 3(10%9) + 8%9=15再比如15:
15 == 1*10 +5
1+5 == 1*(10%9)+5%9 =6得出规律: ab%9%9%9 == ab%9;
参考思路:
https://discuss.leetcode.com/topic/21588/1-line-java-solution
下面给出实现代码:
public static int addDigits_reference(int num) {
return num==0?0:(num%9==0?9: num%9);
}
3. 测试:
//测试用例
public static void main(String[] args) {
LogUtil.log_debug(""+addDigits_reference(38));
}
运行结果:
2017-02-03 23:49:06:2