LeetCode 258. Add Digits

川长思鸟来 2022-07-27 13:39 315阅读 0赞

为了保持了解比较有意思的解法算法,所以决定每天看几道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

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

  1. class Solution {
  2. public:
  3. int addDigits(int num) {
  4. if(num>0)
  5. return num-9*(int)((num-1)/9);
  6. else
  7. return 0;
  8. }
  9. };

发表评论

表情:
评论列表 (有 0 条评论,315人围观)

还没有评论,来说两句吧...

相关阅读