141 x的平方根
原题网址:http://www.lintcode.com/zh-cn/problem/sqrtx/
实现 int sqrt(int x) 函数,计算并返回 x 的平方根。
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(10) = 3
O(log(x))
#include <iostream>
#include <vector>
#include <math.h>
#include <string>
#include <algorithm>
using namespace std; int sqrt(int x)
{
if (x<)
{
return -;
} long long low=,high=x,mid=(low+high)/; //为何用int会出错?;
while (low<=high) //mid*mid有可能超出int范围被截断,小于x,若(mid+1)*(mid+1)被截断后仍小于x,返回错误结果;
{
if (mid*mid==x)
{
return mid;
}
else if (mid*mid>x)
{
high=mid-;
}
else
{
if ((mid+)*(mid+)>x)
{
return mid;
}
else
low=mid+;
}
mid=(low+high)/;
} }
参考:
1 https://blog.csdn.net/gao1440156051/article/details/49766733
2 http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html
141 x的平方根的更多相关文章
- 九章lintcode作业题
1 - 从strStr谈面试技巧与代码风格 必做题: 13.字符串查找 要求:如题 思路:(自写AC)双重循环,内循环读完则成功 还可以用Rabin,KMP算法等 public int strStr( ...
- lintcode 刷题 by python 总结(1)
博主之前在学习 python 的数据结构与算法的基础知识,用的是<problem-solving-with-algorithms-and-data-structure-using-python& ...
- 141. Sqrt(x)【牛顿迭代法求平方根 by java】
Description Implement int sqrt(int x). Compute and return the square root of x. Example sqrt(3) = 1 ...
- 牛顿法求平方根 scala
你任说1个整数x,我任猜它的平方根为y,如果不对或精度不够准确,那我令y = (y+x/y)/2.如此循环反复下去,y就会无限逼近x的平方根.scala代码牛顿智商太高了println( sqr(10 ...
- [LeetCode] Sqrt(x) 求平方根
Implement int sqrt(int x). Compute and return the square root of x. 这道题要求我们求平方根,我们能想到的方法就是算一个候选值的平方, ...
- hdu 4027 2011上海赛区网络赛G 线段树 成段平方根 ***
不能直接使用成段增减的那种,因为一段和的平方根不等于平方根的和,直接记录是否为1,是1就不需要更新了 #include<cstdio> #include<iostream> # ...
- csuoj 1114: 平方根大搜索
http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1114 1114: 平方根大搜索 Time Limit: 5 Sec Memory Limit: ...
- ocp 1Z0-051 141题---感觉有问题
141. View the Exhibit and examine the structure of CUSTOMERS and GRADES tables. You need to display ...
- leetcode 141
141. Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up:Can you sol ...
随机推荐
- notepad++ remove duplicate
step1 to sort and remove space. Since Notepad++ Version 6 you can use this regex in the search and r ...
- IDEA2017.3.1破解激活
idea激活有多种方式,网上较多的是使用注册码或者填License server网址,目前(2017年8月19日)使用注册码的方式,亲测可用的只有lanyun提供的注册码,但是会在2017年11月份的 ...
- Sql Server 小知识不断扩充中
1. char.varchar.nvarchar 区别 char 定长字符数据长度8000字符,小于8000字符时以空格填充. varchar 变长字符数据最大长度8000,小于8000字符时不会以 ...
- JAVA jar命令(一)-jar打包class文件
jar包本质上是将所有class文件.资源文件压缩打成一个包(也可以选择不压缩),可选择在jar包中生成META-INF/MANIFEST.MF文件,MANIFEST.MF是清单文件,里面可以记录主类 ...
- Android NDK Downloads
https://developer.android.google.cn/ndk/downloads/index.html
- TStringGrid 实现下拉框
TStringGrid 实现下拉框比较常见的思路是在TSringGrid中嵌入一个TComboBox ,思路虽然简单,但开发起来却很麻烦,而且有时会出现不愿看到的效果.还有一种更巧的方法,是Delph ...
- NX二次开发-UFUN拾取平面对话框UF_UI_specify_plane
#include <uf.h> #include <uf_ui.h> UF_initialize(); //拾取平面对话框 ] = { , , , , , , , , }; ] ...
- 转-vector与list的区别
转自:C++ vector和list的区别 数据结构的区别 vector vector与数组类似,拥有一段连续的内存空间,并且起始地址不变.便于随机访问,时间复杂度为O(1),但因为内存空间是连续的, ...
- GPIO_F427
- js实现下拉框
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...