前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关关的刷题日记81 – Leetcode 258. Add Digits

关关的刷题日记81 – Leetcode 258. Add Digits

作者头像
WZEARW
发布2018-04-12 14:44:40
5710
发布2018-04-12 14:44:40
举报
文章被收录于专栏:专知专知

关关的刷题日记81 – 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?

题目的意思是给定一个非负整数,不断地重复这个过程:将其每一位数字加起来求和。直到最终得到的结果仅有一位数字。不用循环或者递归能否实现时间复杂度为O(1)的做法?

方法1:写了一个循环版本的。

代码语言:javascript
复制
class Solution {
public:
    int addDigits(int num) {
        int re=0;
        while(1)
        {
            while(num>0)
            {
                re+=num%10;
                num/=10;
            }
            if(re<10)
               return re;   
            num=re;
            re=0;
        }
        return 0;
    }
};

方法2:写了一个递归版本的。

代码语言:javascript
复制
class Solution {
public:
    int addDigits(int num) {
        int re = 0;
        while (num > 0)
        {
            re += num % 10;
            num /= 10;
        }
        if (re < 10)
            return re;
        return addDigits(re);
    }
};

方法3:不用循环或者递归能否实现时间复杂度为O(1)的做法。看了一下答案,这道题实际上是求给定数的树根:a的数根b = ( a - 1) % 9 + 1。

代码语言:javascript
复制
class Solution {
public:
    int addDigits(int num) {
        return (num-1)%9+1;
    }
};

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-12-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 专知 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档