[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 ...
随机推荐
- python3 练习题100例 (十七)四位车号问题
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Fan Lijun' import math for i in range(1 ...
- iOS各个版本的特点
一.导航控制器中: iOS7: 栈顶控制器默认是320*480:控制器有64的高度看不见:
- 基于itchat定制聊天机器人
#coding=utf8import requestsimport itchat #key自己到图灵注册一个 KEY = '************************************** ...
- 2037: [Sdoi2008]Sue的小球
2037: [Sdoi2008]Sue的小球 链接 题解 论文 代码 #include<cstdio> #include<algorithm> #include<cstr ...
- python中全局变量的修改
对于全局变量的修改,如果全局变量是int或者str,那么如果想要在函数中对函数变量进行修改,则需要先在函数内,声明其为global,再进行修改 如果是list或者dict则可以直接修改 a = 1 b ...
- CentOS 7 安装Oracle 11gR2
概述 Oracle 在Linux和window上的安装不太一样,公司又是Linux系统上的Oracle,实在没辙,研究下Linux下Oracle的使用,oracle默认不支持CentOS系统安装,所以 ...
- 快速登录机器&数据库
本文来自网易云社区. 作者:盛国存 背景 我们日常在使用ApiDoc维护管理api文档,提高了api文档的整体维护性.但在老旧接口中,补充接口注解无疑是一次繁重的体力劳动.仔细查看,大多数接口的格式 ...
- 《1024伐木累-周末特别篇》-中彩票了,开发APP
本周发布的<1024伐木累>,受到了很多码汪们的好评,博主在这里感谢大家的支持,同时,博主临时起意,增加一期周末对话特别篇,让大家在“满血复活”的时间里,充分感受快乐的味道~ 1.中彩票 ...
- mysql:用户管理、索引、视图、函数、存储过程
#创建一个用户并设置密码,注意IP地址要是登录mysql电脑的IP地址 USE mysql CREATE USER lisi@'192.168.149.1' IDENTIFIED BY "1 ...
- python 3 使用cmp函数报错
python3 中已经不使用cmp函数进行比较大小,使用operator模块 import operator lt(a,b) 相当于 a<b 从第一个数字或字母(ASCII)比大小 le(a,b ...