LeetCode 258. Add Digits

来源:互联网 发布:清除localstorage数据 编辑:程序博客网 时间:2024/06/07 01:16

Description

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?

Analysis

这个问题叫做Digital root。实际上,随手写几个便会发现,答案序列是这样的:

0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9…

只需要得到上述d(n)的表达式,如下
Congruence formula 1

Congruence formula 2

这两个公式对应了Version 1与Version 2。

Code

Version 1

class Solution {public:    int addDigits(int num) {        if (num == 0) return 0;        return (num % 9 == 0)? 9 : num % 9;    }};

Version 2

class Solution {public:    int addDigits(int num) {        return 1 + (num - 1) % 9;    }};

Appendix

  • Link: https://leetcode.com/problems/add-digits/
  • Run Time:
    • Version 1: 6ms
    • Version 2: 3ms
0 0
原创粉丝点击