LeetCode: Sqrt(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 < 2) return x;

 7         int left = 1;

 8         int right = x >> 1;

 9         int mid;

10         while (left <= right) {

11             mid = (left+right)/2;

12             if (x / mid < mid) right = mid - 1;

13             else left = mid + 1;

14         }

15         return right;

16     }

17 };

 C#

 1 public class Solution {

 2     public int MySqrt(int x) {

 3         if (x < 2) return x;

 4         int left = 1;

 5         int right = x >> 1;

 6         while (left <= right) {

 7             int mid = (left + right) / 2;

 8             if (x / mid < mid) right = mid - 1;

 9             else left = mid + 1;

10         }

11         return right;

12     }

13 }
View Code

 

你可能感兴趣的:(LeetCode)