69 x 的平方根
给你一个非负整数 x ,计算并返回 x 的 算术平方根 。
由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。
注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。
示例 1:
输入:x = 4
输出:2
示例 2:
输入:x = 8
输出:2
解释:8 的算术平方根是 2.82842…, 由于返回类型是整数,小数部分将被舍去。
提示:
0 <= x <= 231 - 1
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sqrtx
解决方案:
提供思路
1)首推pow,现成的方法不用折腾有的没的
2)袖珍计算器算法
3)二分查找
4)牛顿迭代
上代码:
public class Solution {
public int MySqrt(int x) {
double y = Math.Pow(x, 0.5);
int z =Convert.ToInt32(y);
return z;
}
}
public class Solution
{
const double EPSILON = 1e-6;
public int MySqrt(int x)
{
if (x == 0)
{
return 0;
}
bool flag = true;
double sqrt = x;
while (flag)
{
double curr = (sqrt + x / sqrt) / 2;
if (Math.Abs(curr - sqrt) < EPSILON)
{
flag = false;
}
else
{
sqrt = curr;
}
}
return (int)sqrt;
}
}
public class Solution
{
public int MySqrt(int x)
{
if (x == 0)
{
return 0;
}
int low = 1, high = x;
while (low < high)
{
int mid = low + (high - low + 1) / 2;
if ((long)mid * mid <= x)
{
low = mid;
}
else
{
high = mid - 1;
}
}
return low;
}
}
个人感悟:第一段代码还需要取doble前的整数处理,但是这题不一定实用,了解了解方法即可。
以上是碰到的第六十九题,后续持续更新。感觉对你有帮助的小伙伴可以帮忙点个赞噢!