---
# System prepended metadata

title: 69. Sqrt(x)
tags: [Leetcode, binary search, python, c++, easy]

---

###### tags: `Leetcode` `easy` `binary search` `python` `c++`

# 69. Sqrt(x)

## [題目來源:] https://leetcode.com/problems/sqrtx/

## 題目:
Given a non-negative integer x, compute and return the square root of x.

Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

* Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.

## 解題想法:
二分法 head=0 tail=x

## Python:
``` python=
class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        #use二分法找逼近值
        if x==0 or x==1:
            return 0 if x==0 else 1
        high = (x//2)
        low = 0
        middle = (high+low)//2
        while high >= low:
            if (middle*middle) == x:
                return middle
            elif (middle*middle)>x:
                high = middle-1
            else:
                low = middle + 1
            middle = (high+low)//2
        return high


if __name__ == '__main__':
    result = Solution()
    x = 15
    ans = result.mySqrt(x)
    print(ans)
```

## C++:
``` cpp=
#include<iostream>
using namespace std;
class Solution {
public:
    int mySqrt(int x) {
        int head=0;
        int tail=x;
        while (head<=tail){
            long int mid=tail+(head-tail)/2;
            if (mid*mid==x)
                return mid;
            else if (mid*mid>x)
                tail=mid-1;
            else
                head=mid+1;
        }
        return head-1;
    }
};

int main(){
    Solution res;
    int x=8;
    int ans=res.mySqrt(x);
    cout<<ans<<endl;
    return 0;
}

```