258. Add Digits

Posted whl-hl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了258. Add Digits相关的知识,希望对你有一定的参考价值。

1. 问题描述

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?

Hint:

  • A naive implementation of the above process is trivial. Could you come up with other methods?
  • What are all the possible results?
  • How do they occur, periodically or randomly?
  • You may find this Wikipedia article useful.

Tags: Math

Similar Problems: (E) Happy Number

2. 解题思路

 不用 循环递归,毫无思路,从最简单情况开始分析:

  • 对于一位数:0、1、2、3、4、5、6、7、8、9时,返回该数即可
  • 对于两位数:10、11、12、13...,可发现规律,该返回 1 + (num-1)%9
  • 对于三位数:100、101、102、103...,该规律同样适用,该返回 1 + (num-1)%9

3. 代码

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

4. 反思

  • 参考维基百科:https://en.wikipedia.org/wiki/Digital_root

以上是关于258. Add Digits的主要内容,如果未能解决你的问题,请参考以下文章

258. Add Digits

258.Add Digits

leetcode258. Add Digits

258. Add Digits

258.Add Digits

258. Add Digits