---
title: 'LeetCode 69. Sqrt(x)'
disqus: hackmd
---
# LeetCode 69. Sqrt(x)
## Description
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.
## Example
Input: x = 4
Output: 2
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
## Constraints
0 <= x <= 2^31^ - 1
## Answer
此題可用while loop一個一個找,當商比除數小表示剛好超過了次方項,return i - 1即答案。
```Cin=
//2021_11_21
int mySqrt(int x) {
if(x < 2){return x;}
int i = 1;
while(x / i >= i){i++;}
return i - 1;
}
```
另一方法,次方項相當於找因數,而最大的因數除了自己就是x/2了。所以用二元搜尋法來找1~x/2的區域,用除的方式找事為了防止overflow。而return R是因為可以取得較小值。
```Cin=
//2022_03_30
int mySqrt(int x){
if(x < 2){return x;}
int L = 1, R = x/2;
while(L <= R){
int mid = (L+R)/2;
if(x/mid == mid){return mid;}
else if(x/mid > mid){L = mid+1;}
else{R = mid-1;}
}
return R;
}
```
## Link
https://leetcode.com/problems/sqrtx/
###### tags: `Leetcode`