Leetcode 258. Add Digits

258. Add Digits

  • Total Accepted: 108804
  • Total Submissions: 221342
  • Difficulty: Easy

 

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 = 111 + 1 = 2. Since 2 has only one digit, return it.

 

思路:

方法一:按定义做。

方法二:

在b进制中,num≡(num的各位数数字之和) (mod(b-1))。

证明:num=an*bn+an-1*bn-1+...+a1*b+a0。易知,bk≡(b-1+1)k≡1 (mod(b-1))。

所以 num=an*bn+an-1*bn-1+...+a1*b+a≡an+an-1+...+a1+a0 (mod(b-1))。

本题中,b=10。但是也要注意,num mod 9==0时,num本身可以是0。

 

方法三: 方法二的情况可以转化为一个公式:1 + (num - 1) % 9;

 

 

代码:

方法一:

 1 class Solution {
 2 public:
 3     int addDigits(int num) {
 4         while(num/10){
 5             int temp=0;
 6             while(num){
 7                 temp+=num%10;
 8                 num/=10;
 9             }
10             num=temp;
11         }
12         return num;
13     }
14 };

 

 

方法二:

1 class Solution {
2 public:
3     int addDigits(int num) {
4         int res=num%9;
5         return (res!=0||num==0)?res:9;
6     }
7 };

 

 方法三:

1 class Solution {
2 public:
3     int addDigits(int num) {
4         return 1 + (num - 1) % 9;
5     }
6 };

 

 

 

 

posted @ 2016-07-13 22:16  Deribs4  阅读(138)  评论(0编辑  收藏  举报