LeetCode笔记: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 = 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?

大意:

给一个非负数,重复地加其中的数字知道最后只有一个数字。
比如说:
给出数字38,过程类似于:3+8=11,1+1=2.直到2只有一个数字了,就返回它。
继续:
你能不能不用任何循环、递归来在O(1)的时间复杂度中完成它?

思路一:

首先想到的就是循环,对于一个数字,循环将其除以10的余数加起来,直到其是个位数。加完一次后判断是不是只有一个数字,也就是是不是小于10,如果还大于,说明还有多个数字,那就再进行同样的操作。这个方法我自己测试倒是对的,不过leetcode总是说我超时,而且是在11这个数时就超时。。

代码一(c++):

class Solution {
public:
    int addDigits(int num) {
        int tempResult = num;
        while (tempResult > 10) {
            int tempNum = tempResult;
            tempResult = 0;

            for (; tempNum / 10 >= 1;) {
                tempResult += tempNum % 10;
                tempNum = tempNum / 10;
            }
            tempResult += tempNum;
        }
        return tempResult;
    }
};

思路二:

既然题目里也鼓励我们继续思考不用循环的方式,那就一定是有规律可循。我们可以简单地列一下:

数字结果
00
11
22
33
44
55
66
77
88
99
101
112
123
134
145
156
167
178
189
191
202
213

就列这么多了,我们可以发现,结果除了第一个0以外,都在1~9之间循环。而且可以发现,其除以9的余数,为0时,对应的结果是9,而不为0时,余数等于对应的结果,那么代码就呼之欲出啦~

代码二(c++):

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

示例工程:https://github.com/Cloudox/AddDigits
合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值