69. Sqrt(x)
来源:互联网 发布:js获取index 编辑:程序博客网 时间:2024/06/18 12:02
Problem:
Implement int sqrt(int x).
Compute and return the square root of x.
题意是要我们自己写一个开方的函数。我一开始写直接用很朴素的算法,从count=0开始,每次+1,暴力算法。结果是对的,但是结果是超时了。后来我就开始想其他办法,后来看到处理的是int型的,MAX_INT的开方是46340,所以打算用分治递归的方法,每次折半,找到符合的就return,假如input的值更大,就把begin设为count, end就是传进来的end,一直递归到找到结果。后来发现有一个bug,就是样例输入是MAX_INT-1的时候出错了,因为(46399,46400)折中结果一直会是46399,但是输入样例2147395600结果应该是46400,所以吧一开始初始化的46340+1就好了。
Code:
class Solution {public: int mySqrt(int x) { int count = 46341; //sqrt root of MAX_INT = 46340. return recursionDivide(0, count, x); } int recursionDivide(int begin, int end, int input) { int count = (begin + end) / 2; if (count * count == input) { return count; } if (count == begin || count == end) { return count; } if (input > count * count) { return recursionDivide(count, end, input); } else { return recursionDivide(0, count, input); } }};
阅读全文
0 0
- LeetCode 69. Sqrt(x)
- LeetCode 69.Sqrt(x)
- LeetCode --- 69. Sqrt(x)
- [Leetcode] 69. Sqrt(x)
- [leetcode] 69.Sqrt(x)
- 69.Sqrt(x)
- 69. Sqrt(x)
- Leetcode-69.Sqrt(x)
- leetcode--69.sqrt(x)
- 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- leetcode 69. Sqrt(x)
- 【LeetCode】69. Sqrt(x)
- 69. Sqrt(x) LeetCode
- 69. Sqrt(x)
- 69. Sqrt(x)
- [leetcode] 69. Sqrt(x)
- 69. Sqrt(x)
- Hibernate总结
- 原型链及作用域知识图解
- java链表算法题一
- cloudnote_yanshijun
- springboot对于redis的增删改查
- 69. Sqrt(x)
- java多线程小结
- (项目笔记) 相对路径、绝对路径以及虚拟路径
- [阿里云] Linux CentOS 7.3 环境下安装 MySql5.7 全程讲解以及常见问题的解决方法
- 常见的DOS命令
- Django 开发学习笔记(8)- 开发表单页面,让用户添加内容
- 函数的四种调用模式(this的指向)
- should use @string resource / android 控件名称
- Go获取类型底层类型