Leetcode 69. Sqrt(x)

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 69. Sqrt(x)_第1张图片
Sqrt(x)

2. Solution

  • Binary Search
class Solution {
public:
    int mySqrt(int x) {
        int left = 0;
        int right = x;
        while(left <= right) {
            long mid = (left + right) / 2;
            long square = mid * mid;
            if(square == x) {
                return mid;
            }
            if(square > x) {
                right = mid - 1;
            }
            else {
                left = mid + 1;
            }
        }
        return right;
    }
};
  • Newton's Method
class Solution {
public:
    int mySqrt(int x) {
        long y = x;
        while(y * y > x) {
            y = (y + x / y) / 2;
        }
        return y;
    }
};

Reference

  1. https://leetcode.com/problems/sqrtx/description/

你可能感兴趣的:(Leetcode 69. Sqrt(x))