标签:
Implement int sqrt(int x)
.
Compute and return the square root of x.
自己的代码:
1 int mySqrt(int x) { 2 if(x == 0 || x == 1) 3 return x; 4 int begin = 0; 5 for(long long i = x / 2; i > 0; i /= 2){ 6 if(i * i == x) 7 return i; 8 if(i *i < x){ 9 begin = i; 10 break; 11 } 12 } 13 for(long long i = begin * 2; i > begin; i--){ 14 if(i * i <= x) 15 return i; 16 } 17 }
discuss方法:
class Solution { public: int mySqrt(int x) { if(x <= 1) return x; int left = 1, right = x; while(left < right) { int mid = left + (right - left) / 2; if(mid <= x / mid ) { //这里使用除,是为了方式mid * mid时大过int限制 left = mid + 1; } else { right = mid; } } return left - 1; } };
标签:
原文地址:http://www.cnblogs.com/dylqt/p/5204588.html