258_Add Digits

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.

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

  假设这个整数有5位,   ABCED, n = A * 10000 + B * 1000 + C * 100 + D * 10 + E * 1

                    =(A + B + C + D + E) + A * 9999 + B * 999 + C * 99 + D * 9

                    =(A + B + C + D + E) + 9 * [(A * 1111) + (B * 111) + (C * 11) + (D * 1)]

                    =(A + B + C + D + E) + Q

              Q一定可以被9整除

              假设 A + B + C + D + E的结果有两位,设为 m = FG

                  m = 10 * F + G

                    = (F + G) + 9 * F

                    = (F + G) + P

              P 一定可以被9整除

  若此时D+E为个数,则结束了

  (n % 9) 为最终结果

  但是, n % 9  最大值为8, 不可以为9

  

  所以,最终结果为:   (n - 1) % 9 + 1

1 class Solution {
2 public:
3   int addDigits(int num) {
4     return (num - 1) % 9 + 1;
5   }
6 };

  

原文地址:https://www.cnblogs.com/Anthony-Wang/p/4997565.html