[LeetCode]: 258: Add Digits
2015-09-02 22:39
295 查看
题目:
Given a non-negative integer
For example:
Given
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
分析:
需要时间复杂度是O(1),所以需要分析规律
经过计算1~30,得出结论:结果在1~9之间,提交代码为:
但是结果报错,发现遗忘了输入为0的情况,修改代码为:
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
2has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
分析:
需要时间复杂度是O(1),所以需要分析规律
经过计算1~30,得出结论:结果在1~9之间,提交代码为:
public static int addDigits(int num) { int intRsult = num%9; if(intRsult == 0){ intRsult =9; } return intRsult; }
但是结果报错,发现遗忘了输入为0的情况,修改代码为:
public: int addDigits(int num) { return 1 + (num-1)%9; } };
相关文章推荐
- MinGW+MSYS环境编译Linphone的SDK
- 【SSM】spring与mybatis三种整合方法
- Linux串口编程教程(三)——串口编程详解
- MySQL(九)之MySQL存储引擎
- static变量与static的用法
- cocos2d-x 3.0学习-创建菜单场景
- 操作系统之面试常考(后期补充)
- 如何复制assets中的数据库文件并访问数据库
- 【《Objective-C 高级编程》 学习笔记--GCD】
- [Leetcode]Minimum Window Substring
- MAC 下终端打开app
- 黑马程序员——多线程9:其他线程技术-下
- 精品软件 推荐 Bootice(引导扇区维护工具)
- 精品软件 推荐 Bootice(引导扇区维护工具)
- SSH 免密码登陆
- 用Android Studio进行NDK开发(简化流程)
- "Python"学习笔记(一)
- 计算机视觉与模式识别 code
- 直线,折线,封闭曲线,平面分割区域问题
- Hanoi汉诺塔问题