x的平方根
class Solution { public: /** * @param x: An integer * @return: The sqrt of x */ int getResult(long start, long end, long target){ long temp; while(start <= end){ temp = (start + end) / 2; if(start * start > target) return start -1; if(end * end < target) return end; if(temp * temp == target) return temp; else if(temp * temp > target) end = temp -1; else if(temp * temp < target) start = temp + 1; } } int sqrt(int x) { // write your code here if(x == 0) return 0; else if(x <= 3) return 1; else if(x > 3) return getResult(3, x/2+1 ,x); } };
ps:注意int越界