[LeetCode] Sqrt(x) 二分搜索
并未使用牛顿迭代,实现是通过二分搜索实现的,需要注意判断时候 x* x<K 容易溢出,所以可以改为 x< k/x。
#include <iostream>
using namespace std; class Solution {
public:
int sqrt(int x) {
if(x <) return x;
int lft = ,rgt = x;
int mid = (lft+rgt)/;
while(lft+<rgt){
if(mid == x/mid) return mid;
if(mid < x/ mid){
lft = mid;
}
else{
rgt = mid;
}
mid = (lft+rgt)/;
}
if( rgt<=mid/rgt) return rgt;
return lft;
}
}; int main()
{
Solution sol;
for(int i =;i<;i++)
cout<<sol.sqrt(i)<<endl;
return ;
}
[LeetCode] Sqrt(x) 二分搜索的更多相关文章
- [LeetCode] Sqrt(x) 求平方根
Implement int sqrt(int x). Compute and return the square root of x. 这道题要求我们求平方根,我们能想到的方法就是算一个候选值的平方, ...
- Leetcode Sqrt(x)
参考Babylonian method (x0 越接近S的平方根越好) class Solution { public: int sqrt(double x) { ) ; , tolerance ...
- leetcode—sqrt
1.题目描述 Implement int sqrt(int x). Compute and return the square root of x. 2.解法分析 很明显,用二分搜索可解,但是 ...
- [leetcode]Sqrt(x) @ Python
原题地址:https://oj.leetcode.com/problems/sqrtx/ 题意: Implement int sqrt(int x). Compute and return the s ...
- [Leetcode] sqrt 开根号
Implementint sqrt(int x). Compute and return the square root of x. 题意:求根号下x 的值 思路:使用二分搜索.先定义x平方根的取值区 ...
- LeetCode: Sqrt
Title: Implement int sqrt(int x). Compute and return the square root of x. 思路:这个平方根肯定是在[1,x]之间,所以在这个 ...
- LeetCode:Sqrt(x) 解题报告
Sqrt(x) Implement int sqrt(int x). Compute and return the square root of x. SOLUTION 1: 参见:二分法总结,以及模 ...
- LeetCode——Sqrt(x)
Description: Implement int sqrt(int x). Compute and return the square root of x. 好好学习数学还是非常有用的,牛顿迭代法 ...
- [LeetCode] Insert Interval 二分搜索
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessa ...
随机推荐
- ubuntu安装tomcat7
1. 下载apache-tomcat-7.0.64.tar.gz 进入tomcat官网:http://tomcat.apache.org/download-70.cgi下载相应的压缩包: 2. 上传安 ...
- 基于appium的app自动化测试框架
基于appium框架的app自动化测试 App自动化测试主要难点在于环境的搭建,appium完全是基于selenium进行的扩展,所以app测试框架也是基于web测试框架开发的 一.设备连接 (即构建 ...
- MySQL触发器和更新操作
一.触发器概念 触发器(trigger):监视某种情况,并触发某种操作,它是提供给程序员和数据分析员来保证数据完整性的一种方法,它是与表事件相关的特殊的存储过程,它的执行不是由程序调用,也不是手工启动 ...
- K-均值聚类——电影类型
K-均值聚类 K-均值算法试图将一系列样本分割成K个不同的类簇(其中K是模型的输入参数),其形式化的目标函数称为类簇内的方差和(within cluster sum of squared errors ...
- 15.8,redis-cluster配置
为什么要用redis-cluster 1.并发问题 redis官方生成可以达到 10万/每秒,每秒执行10万条命令假如业务需要每秒100万的命令执行呢? 2.数据量太大 一台服务器内存正常是16~ ...
- 19,Ubuntu安装之python开发
什么??公司要用Ubuntu(乌班图)?不会用??怎么进行python开发??? 乌班图操作系统下载地址:http://releases.ubuntu.com/18.04/ubuntu-18.04 ...
- Apache 多端口配置方法
首先修改httpd.conf配置文件. 添加8080端口 Listen 8080 打开虚拟配置文件 # Virtual hosts Include conf/extra/httpd-vhosts.co ...
- Spark Streaming实例
Spark Streaming实例分析 2015-02-02 21:00 4343人阅读 评论(0) 收藏 举报 分类: spark(11) 转载地址:http://www.aboutyun.co ...
- github+git提交 基础用法
git版本管理基本用法: 安装就不用说了 随便一搜 安装完 妥妥的.下边说的是在github从新建一个项目开始: 1.首先打开自己的github地址,如下图所示 点加号 选 New repositor ...
- 解决idea无法下载插件的问题
分析原因: 使用了 https 协议下载而导致的问题. 解决办法: 找到 File -> Settings -> Appearance & Behavior -> Syste ...