LeetCode编程练习 - Add Digits学习心得

题目:

    Given a non-negative integernum, 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. Since2 has only one digit, return it.

      Follow up:
      Could you do it without any loop/recursion in O(1) runtime?

   给定一个非负整数num,不断的将其所有的数字相加,直到结果只有一个数字。例如,给定num = 38,流程为3 + 8 =11,1 + 1 = 2,因为2只有一个数字,返回它。


思路:

   之前有遇到一道题“快乐数”,性质差不多,先判断这个数是不是一个正整数,然后定义一个哈希集来保存中间相加的结果,然后判断数值是不是小于10。使用辗转相除法

LeetCode编程练习 - Add Digits学习心得


    运行后的结果对于大于10来说得出的结果是正确,但是小于10输出结果为0,突然发现没有把小于和等于10的情况考虑进去。

LeetCode编程练习 - Add Digits学习心得


     我的思路相对来说比较容易理解,按照循环模拟的方法来写,并没有考虑到O(1)。解决方案中以对数值除9取余做判断,得到一个规律,所有的数相加后得到的数都是0-9.

LeetCode编程练习 - Add Digits学习心得