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);        }    }};


如果大家还有更好的解法,可以一起讨论,虚心受教。