Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

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

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
  the decimal part is truncated, 2 is returned.

这道题要求我们求平方根,我们能想到的方法就是算一个候选值的平方,然后和x比较大小,为了缩短查找时间,我们采用二分搜索法来找平方根,这里属于博主之前总结的 LeetCode Binary Search Summary 二分搜索法小结 中的第三类的变形,找最后一个不大于目标值的数,这里细心的童鞋可能会有疑问,在总结贴中第三类博主的 right 用的是开区间,那么这里为啥 right 初始化为x,而不是 x+1 呢?因为总结帖里的 left 和 right 都是数组下标,这里的 left 和 right 直接就是数字本身了,一个数字的平方根是不可能比起本身还大的,所以不用加1,还有就是这里若x是整型最大值,再加1就会溢出。最后就是返回值是 right-1,因为题目中说了要把小数部分减去,只有减1才能得到正确的值,代码如下:

解法一:

class Solution {
public:
int mySqrt(int x) {
if (x <= ) return x;
int left = , right = x;
while (left < right) {
int mid = left + (right - left) / ;
if (x / mid >= mid) left = mid + ;
else right = mid;
}
return right - ;
}
};

这道题还有另一种解法,是利用牛顿迭代法,记得高数中好像讲到过这个方法,是用逼近法求方程根的神器,在这里也可以借用一下,可参见网友 Annie Kim's Blog的博客,因为要求 x2 = n 的解,令 f(x)=x2-n,相当于求解 f(x)=0 的解,可以求出递推式如下:

xi+1=xi - (xi- n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2

解法二:

class Solution {
public:
int mySqrt(int x) {
if (x == ) return ;
double res = , pre = ;
while (abs(res - pre) > 1e-) {
pre = res;
res = (res + x / res) / ;
}
return int(res);
}
};

也是牛顿迭代法,写法更加简洁一些,注意为了防止越界,声明为长整型,参见代码如下:

解法三:

class Solution {
public:
int mySqrt(int x) {
long res = x;
while (res * res > x) {
res = (res + x / res) / ;
}
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/69

类似题目:

Pow(x, n)

Valid Perfect Square

参考资料:

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

https://leetcode.com/problems/sqrtx/discuss/25130/My-clean-C++-code-8ms

https://leetcode.com/problems/sqrtx/discuss/25047/A-Binary-Search-Solution

https://leetcode.com/problems/sqrtx/discuss/25057/3-4-short-lines-Integer-Newton-Every-Language

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 69. Sqrt(x) 求平方根的更多相关文章

  1. LeetCode 69. Sqrt(x) (平方根)

    Implement int sqrt(int x). Compute and return the square root of x. x is guaranteed to be a non-nega ...

  2. LeetCode 069 Sqrt(x) 求平方根

    Implement int sqrt(int x).Compute and return the square root of x.x is guaranteed to be a non-negati ...

  3. Leetcode 69. Sqrt(x)及其扩展(有/无精度、二分法、牛顿法)详解

    Leetcode 69. Sqrt(x) Easy https://leetcode.com/problems/sqrtx/ Implement int sqrt(int x). Compute an ...

  4. C++版 - Leetcode 69. Sqrt(x) 解题报告【C库函数sqrt(x)模拟-求平方根】

    69. Sqrt(x) Total Accepted: 93296 Total Submissions: 368340 Difficulty: Medium 提交网址: https://leetcod ...

  5. [LeetCode] Sqrt(x) 求平方根

    Implement int sqrt(int x). Compute and return the square root of x. 这道题要求我们求平方根,我们能想到的方法就是算一个候选值的平方, ...

  6. 069 Sqrt(x) 求平方根

    实现 int sqrt(int x) 函数.计算并返回 x 的平方根.x 保证是一个非负整数.案例 1:输入: 4输出: 2案例 2:输入: 8输出: 2说明: 8 的平方根是 2.82842..., ...

  7. Leetcode 69. Sqrt(x)

    Implement int sqrt(int x). 思路: Binary Search class Solution(object): def mySqrt(self, x): "&quo ...

  8. (二分查找 拓展) leetcode 69. Sqrt(x)

    Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a no ...

  9. [LeetCode] 69. Sqrt(x)_Easy tag: Binary Search

    Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a no ...

随机推荐

  1. Java Exception 异常处理

    一.定义 异常(Exception) : 是指程序运行时出现的非正常情况,是特殊的运行错误对象,对应着Java语言特定的运行错误处理机制. 二.两大常见的异常类型 • RuntimeException ...

  2. 【linux】glibc升级

    glibc升级 步骤如下: 1.下载解压glibc wget http://ftp.gnu.org/gnu/glibc/glibc-2.18.tar.gz tar zxvf glibc-2.18.ta ...

  3. 联合 CNCF 共同出品:Kubernetes and Cloud Native Meetup 成都站

    亮点解读 云原生前沿技术分享:阿里经济体“云原生化”宝贵经验与最佳实践成果 OpenKruise 价值几何? 防踩坑指南:国内知名容器平台架构师解读从 ECS 迁移到 K8S 走过哪些坑. ​云原生服 ...

  4. C# 协变、逆变

    微软官方概述: 在C#中,协变和逆变能够实现数组类型.委托类型和泛型类型参数的隐式引用转换.协变保留分配兼容性,逆变则与之相反. 协变:能够使用与原始指定的派生类型相比,派生程度更大的类型. 逆变:能 ...

  5. Python - 条件控制、循环语句 - 第十二天

    Python 条件控制.循环语句 end 关键字 关键字end可以用于将结果输出到同一行,或者在输出的末尾添加不同的字符,实例如下: Python 条件语句是通过一条或多条语句的执行结果(True 或 ...

  6. nodejs-翻转算法

    nodejs-翻转算法 /** * Created by moon on 2019/12/14. */ //程序运行完成时一定要有输出语句,本工具才能正确展示运行结果. function abc() ...

  7. vue-router 在项目中的使用

    一.下载vue-router npm install vue-router --save 二.编码 1.在项目中新建文件夹 router/index.js /* * 路由对象模块 * */ impor ...

  8. JavaScript中的 JSON 和 JSONP

    JSON 和 JSONP JSONP是一种发送JSON数据的方法,无需担心跨域问题.JSONP不使用该XMLHttpRequest对象.JSONP使用<script>标签代替.由于跨域策略 ...

  9. PC端页面适应不同的分辨率的方法

    原文链接:https://www.jianshu.com/p/4850a7b22228 一.根据不同的分辨率,加载不同的CSS样式文件 这个方法的思路是,分别针对800.1280.1440.1600. ...

  10. Qt for Android使用grpc探索

    利用Qt在Android上使用grpc需要*.a的静态库,Windows上编译的lib库以及linux编译出来的.a,经过尝试,均无法链接成功.本文尝试使用NDK来编译Android版本的grpc静态 ...