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

点击上方“专知”,关注获取专业AI知识”

关关的刷题日记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:写了一个循环版本的。

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:写了一个递归版本的。

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。

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

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

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

专知网站查看Leetcode刷题日记:



请登录www.zhuanzhi.ai或者点击阅读原文,顶端搜索“Leetcode” 主题,取查看获得专知Leetcode所有资源!如下图所示~ 



 请感兴趣的同学,扫一扫下面群二维码,加入到专知-LeetCode学习交流群!(注明 Leetcode 刷题)




欢迎转发到你的微信群和朋友圈,分享专业AI知识!


获取更多关于机器学习以及人工智能知识资料,请访问www.zhuanzhi.ai,  或者点击阅读原文,即可得到!


-END-

欢迎使用专知

专知,一个新的认知方式!专注在人工智能领域为AI从业者提供专业可信的知识分发服务, 包括主题定制、主题链路、搜索发现等服务,帮你又好又快找到所需知识。


使用方法>>访问www.zhuanzhi.ai, 或点击文章下方“阅读原文”即可访问专知

中国科学院自动化研究所专知团队

@2017 专知

专 · 知


关注我们的公众号,获取最新关于专知以及人工智能的资讯、技术、算法、深度干货等内容。扫一扫下方关注我们的微信公众号。

点击“阅读原文”,使用专知

展开全文
Top
微信扫码咨询专知VIP会员