LeetCode 258. Add Digits

为了保持了解比较有意思的解法算法,所以决定每天看几道LeetCode上面的题,现在开始:
题目:
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.

题目的大致意思是:
有一个非负的整形数字,将它的所有位数相加得到一个新的数字,如果得到的新的数字不是一位数,就重复这个过程,直到个位数;

拿到这个题目很想当然的想到了递归神马的,但是看见题目给了一个要求,就不知道是什么怎么弄了,这个题目的要求是:
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
意思是:你能不能不通过递归或者循环实现,而且算法的时间是O(1)。

所以估计这个题目很可能就是数字规律的问题了,然后LeetCode给了思路,一篇维基百科上面的文章,是讲关于digital root的文章。文章的网址是:https://en.wikipedia.org/wiki/Digital_root

根据这篇文章的内容,也就是一个公式,然后写了下面的代码:

class Solution {
public:
    int addDigits(int num) {
        if(num>0)
        return num-9*(int)((num-1)/9);
        else
        return 0;
    }
};

你可能感兴趣的:(LeetCode 258. Add Digits)