【一天一道LeetCode】#258. Add Digits

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(一)题目

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?

(二)解题

题目大意:给定一个非负数,对每一位进行相加,得到的和继续位相加,直到和为一位数为止

解题思路一

一开始,顺着题目的意思写下如下循环:

class Solution {
public:
    int addDigits(int num) {
        int ret = num;
        while(ret>=10)
        {
            int sum = 0;
            int temp = ret;
            while(temp){//每次计算每一位上的和
                sum+=temp%10;
                temp/=10;
            } 
            ret = sum;
        }
        return ret;
    }
};

循环很简单,计算每一位的和,判断和是否为一位数,依次循环。

后来,突然看到题目中写了:Could you do it without any loop/recursion in O(1) runtime?

什么?O(1)时间!不用循环!下面看解法二的思路。

解题思路二

既然不用循环,就开始找规律,发现一直是1-9在循环,所以很容易想到mod9

要注意以下两个特殊情况:

(1) 0的时候为0
(2) mod9==0,此时返回9(除0外)

class Solution {
public:
    int addDigits(int num) {
        if(num==0) return 0;//特殊情况0
        return num%9==0?9:num%9;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值