258. Add Digits
2016-05-13 14:13
239 查看
258. Add Digits
Description:Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Could you do it without any loop/recursion in O(1) runtime?
Example:
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Hint:
1. A naive implementation of the above process is trivial. Could you come up with other methods?
2. What are all the possible results?
Link:
https://leetcode.com/problems/add-digits/
Analysis:
1. 针对这个题目,第一反应是使用递归。但是题目已经说明时间复杂度为O(1)。所以就要换个思路了。碰到这种问题还是可以先多尝试几个数,随便试一下。
2. 这道题其实还是不太好想的(反正我是没想出来,看网上的答案,哈哈),需要用到一个技巧:
A.首先,假设num1为一五位数,
则num1=(a+b+c+d+e)+(a*9999+b*999+c*99+d*9),且num1%9=(a+b+c+d+e)%9;
B.而(a+b+c+d+e)可能仍然大于9,令其等于num2;
即(a+b+c+d+e)=num2=(f+g)+(f*9),有num1%9=(f+g)%9;
C.这里假设num3=(f+g),值小于等于9(这样总会化简到1~9之间的数),则num1%9=num3%9,而num3正是num1各位数累加的结果,也就是我们想要得到的值。
D.但是注意一点,我们通过num1%9只能得到num3%9而非num3,所以我们还需要最后一步处理(注意最后一列):
num3%9: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 0 |
---|---|---|---|---|---|---|---|---|---|
num3: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Source Code(C++):
#include <iostream> using namespace std; class Solution { public: int addDigits(int num) { if (num==0) { return 0; } else { // return (num-1)%9+1; int k = num%9; if (k==0){ return 9; } else{ return k; } } } }; int main() { Solution s; cout << s.addDigits(38); return 0; }
相关文章推荐
- iOS实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像
- 数据库缓存字节数超过128K
- C++ Cross Platform Memory Leak Detector
- java学生成绩管理系统
- MySQL高可用架构在业务层面的分析研究
- hive map side join
- ThreadLocal教程
- 人脸检测之Joint Cascade Face Detection and Alignment 笔记---ECCV2014
- 如何自定义验证器?
- jQuery-瀑布流-绝对定位布局(二)(延迟AJAX加载图片)
- JS继承机制的深入理解--动态原型存在的问题与解决
- Annotation Processor - How to get the Class it is processing
- Android Studio编译报错:sdk:minSdkVersion 1 cannot be smaller than version 7 declared in library
- EPC-6708 arm 开发板常用命令等
- Attribute value is quoted with " which must be escaped when used within the value 问题解决
- jQuery-瀑布流-浮动布局(一
- ueditor之ruby on rails 版
- mac idea(intellij idea)常用快捷键
- [ios]字符串不同位置显示不同颜色
- linux sshd远程登陆配置