https://oj.leetcode.com/problems/sqrtx/
求一个数的开方,二分查找一个数,直到这个数的平方 - target 小于 0.001。
但这道题出的不好,返回值竟然是 int ,脑洞太大了。
class Solution { public: int sqrt(int x) { if(x<=0) return 0; if(x == 1) return 1; double fi = 0.0001; //binary search double low = 0, high = x, middle = x/2; while(1) { if(abs(middle*middle - x) < fi) return middle; if(middle*middle > x) high = middle; else if(middle*middle<x) low = middle; middle= (low + high)/2.0; } } };