标签:
Add Digits: 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.
题意:将给定的整数各个位数相加,直到相加之和小于10。
思路:(1)常规的解法,求和之后进行判断,然后在进行求和直至满足条件;(2)参考Digital root的定义进行求解。
代码:
第一种思路:
//求整数的各位之和 public int get_sum(int sum) { int count = 0; while(sum>0){ count = count + sum%10; sum/=10; } return count; } public int addDigits(int num) { int sum=0; while(true) { sum= get_sum(num); if(num<=9) { return sum; } else { num = sum; } } }
第二种思路:
public int addDigits(int num) { if (num == 0) return 0; if (num%9==0) return 9; if(num<9) { return num; }else{ return addDigits(num % 9); } }
标签:
原文地址:http://www.cnblogs.com/Lewisr/p/5122343.html