码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 258 Add Digits

时间:2016-08-03 13:13:19      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

LeetCode 258 Add Digits

标签:

原文地址:http://www.cnblogs.com/wood-python/p/5732236.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!