LeetCode 之 Add Digits
2015-11-18 23:29
183 查看
Given a non-negative integer
one digit.
For example:
Given
only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
LeetCode前面的题都比较简单,有几个是关于数字规律的,如果能找到的话,很快就能解决,难度不在代码上的。最基本的方法是列举法从0到30我们就能很确定规律了:ans是以9为周期的,所以代码如下:
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
2has
only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
LeetCode前面的题都比较简单,有几个是关于数字规律的,如果能找到的话,很快就能解决,难度不在代码上的。最基本的方法是列举法从0到30我们就能很确定规律了:ans是以9为周期的,所以代码如下:
class Solution { public: int addDigits(int num) { return (num-1)%9+1; } };其实最开始想到的是递归求每一位,再求和。但是我看Follow up中说有O(1)runtime的算法,所以可以直接找规律了。如果要证明的话就要用数论的知识了,这个以后再说吧。
相关文章推荐
- 正则表达式的匹配
- 数独游戏的简单回溯解法
- 理解 JavaScript Scoping & Hoisting(二)
- Java parseInt实现
- 第22篇 js中的this指针的用法
- git命令总结
- python之自动生成图像列表
- Git入门及上传项目到github中
- kali安装pip包遇到问题以及解决方法
- Git入门及上传项目到github中
- UVa-1598-Exchange
- Spring中id和idref属性的区别
- 第21篇 js四种继承方式
- MySQL 实现 lastindexof 的方法
- 如何才能学到Qt的精髓(信号槽之间的无关性),QT的GUI全是自己的一套,并且完全开源,提供了一个绝好机会窥视gui具体实现
- ffmpeg 基本数据结构和对象(一): AVPacket、AVPicture、AVFrame
- 第20篇 js高级知识---深入原型链
- MAC上反编译android apk---apktool, dex2jar, jd-jui安装使用(含手动签名)
- 二叉搜索树ADT_BSTree
- 关于我和我的工作