LeetCode:Add Digits - 非负整数各位相加

1、题目名称

Add Digits (非负整数各位相加)

2、题目地址

https://leetcode.com/problems/add-digits/

3、题目内容

英文:Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

中文:有一个非负整数num,重复这样的操作:对该数字的各位数字求和,对这个和的各位数字再求和……直到最后得到一个仅1位的数字(即小于10的数字)。

例如:num=38,3+8=11,1+1=2。因为2小于10,因此返回2。

4、解题方法

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

 

posted @ 2016-03-04 18:55  Hutonm  阅读(228)  评论(0编辑  收藏  举报