Title Description
Implement int sqrt(int x)
functions.
Computes and returns x square root, wherein x is a non-negative integer.
Since the return type is an integer, the integer part of the result to retain only the fractional part is rounded down.
Example 1:
输入: 4
输出: 2
Example 2:
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。
analysis
The square root of self-realization. Methods as below:
Cycle of violence
class Solution {
public:
int mySqrt(int x) {
long long res = 0;
for (long long i = 0; i < x; i++) {
if ((i * i) == x) {res = i; break;}
long long tmp = i + 1;
if ((tmp * tmp) > x) {res = i; break;}
if ((tmp * tmp) == x) {res = tmp; break;}
}
return res;
}
Library Functions
C++: return sqrt(x);
Java: return int(math.sqrt(x))
Binary search
class Solution {
public:
int mySqrt(int x) {
long long begin = 0;
long long end = x / 2 + 1;
long long mid;
long long res;
while (begin <= end) {
mid = (begin + end) / 2;
res = mid * mid;
if (res == x) return mid;
if (res < x) begin = mid + 1;
if (res > x) end = mid -1;
}
return end;
}
Newton iteration
class Solution {
public:
int mySqrt(int x) {
if (x == 0) return 0;
double flag = 0;
double res = 1;
while (res! = flag)
{
flag = res;
res = (res + x / res ) / 2;
}
return int(res);
}
};
reference
Newton iterative learning:
https://www.cnblogs.com/grandyang/p/4346413.html
https://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html