标签:
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.
思路:
有通常的循环法解,网上查资料之后得知可以转为一个数学问题题解。
解法:
1.普通循环法
1 public class Solution 2 { 3 public int addDigit(int number) 4 { 5 if(number < 10) 6 return number; 7 else 8 { 9 int sum = 0; 10 while(number >= 10) 11 { 12 sum += number % 10; 13 number = number / 10; 14 } 15 sum += number; 16 return addDigit(sum); 17 } 18 } 19 }
2.数学解法
1 public class Solution 2 { 3 public int addDigit(int number) 4 { 5 if(number == 0) 6 return 0; 7 else if(number % 9 == 0 && number != 0) 8 return 9; 9 else if(number % 9 != 0) 10 return n % 9; 11 } 12 }
标签:
原文地址:http://www.cnblogs.com/wood-python/p/5732236.html