LeetCode No.258 Add Digits

来源:互联网 发布:网络平台借贷违法的吗 编辑:程序博客网 时间:2024/06/01 08:07

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.

===================================================================

题目链接:https://leetcode.com/problems/add-digits/

题目大意:计算num各个位的数字之和,直到最终结果是一位数。

思路:递归计算。

参考代码:

class Solution {public:    int addDigits(int num) {        if ( num < 10 )            return num ;        int ans = 0 ;        while ( num )        {            ans += ( num % 10 ) ;            num /= 10 ;        }        return addDigits ( ans ) ;    }};


0 0