Implement int sqrt(int x)
.
Compute and return the square root of x.
简单的二分法,注意mid应该选为long,否则容易溢出:
1 class Solution { 2 public: 3 int mySqrt(int x) { 4 if(x == 0 || x == 1) return x; 5 int beg = 1; 6 int end = x; 7 long mid = 0; //这里用long,否则会溢出 8 while(beg <= end){ 9 mid = beg + (end - beg)/2; 10 if(mid * mid < x){ 11 beg = mid + 1; 12 }else if(mid * mid > x){ 13 end = mid - 1; 14 }else{ 15 return mid; 16 } 17 } 18 return end; 19 } 20 };
时间: 2024-11-03 05:39:27