LeetCode #258 - Add Digits -Easy

Problem

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Hints:

  • 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.

Example

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Algorithm

给定一个非负整数num,将num 的每一位数字加起来。若加起来的和只有一位,则返回;若加起来的和有两位或两位以上的数字,则重复每一位数字求和过程,直到和只有一位数字。

首先看到题目即可写出O(n^2)的解法。若num大于10,则把每一位数字加起来;否则直接返回。

代码如下

//版本1,时间复杂度O(n^2)
class Solution {
public:
    int addDigits(int num) {
        if(num<10) return num;
        int sum=0;
        while(num/10>0){
            sum=0;
            while(num){
                sum+=(num%10);
                num/=10;
            }
            num=sum;
        }
        return sum;
    }
};

然而题目中的Hint部分问是否存在O(1)的解法。要在O(1)时间内解决问题,一般都是存在某种规律。于是对结果进行枚举。枚举过程如下。

numreturnnumreturn
11112
22123
33134
44145
55156
66167
77178
88189
99191
101202

可以发现num中每九个数,return就循环一次。于是可通过模9的方法直接得到返回值。

代码如下

//版本2,时间复杂度O(1)
class Solution {
public:
    int addDigits(int num) {
        if(num==0) return 0;
        if(num%9==0) return 9;
        else return num%9;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值