Implement int sqrt(int x)
.
Compute and return the square root of x.
1 class Solution { 2 public: 3 int sqrt(int x) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if(x<=0) return 0; 7 if(x==1) return 1; 8 int small=0; 9 int large=x; 10 int temp=x/2; 11 while(small<large){ 12 int a = x/temp; 13 int b = x/(temp+1); 14 if (a==temp) return a; 15 if (b==temp+1) return b; 16 if(temp<a && temp+1>b) 17 return temp; 18 else if(temp<a && temp+1<b){ 19 small=temp+1; 20 temp = (small+large)/2; 21 }else { 22 large = temp; 23 temp = (small+large)/2; 24 } 25 } 26 return -1; 27 } 28 };
思路:需要在O(log n)时间内实现,并且注意用除法,防止两个int型的数相乘超过int的范围。