Sqrt(x) 求平方根@LeetCode
2013-11-11 02:58
423 查看
二分法
package Level4;
/**
* Sqrt(x)
*
* Implement int sqrt(int x).
*
* Compute and return the square root of x.
*
*/
public class S69 {
public static void main(String[] args) {
System.out.println(sqrt(2));
}
public static int sqrt(int x) {
double diff = 0.01; // 误差
int low = 0;
int high = x;
while(low <= high){
// 注意越界!所以用double来存
double mid = low + (high-low)/2;
if(Math.abs(mid*mid-x) <= diff){
return (int)mid;
}else if(x > mid*mid+diff){
low = (int)mid+1;
}else if(x < mid*mid-diff){
high = (int)mid-1;
}
}
// 当找不到时候,这是low,high指针已经交叉,取较小的,即high
return high;
}
}
public class Solution {
public int sqrt(int x) {
int left = 0, right = x;
while(left <= right) {
double mid = left + (right-left)/2;
double mul = mid * mid;
if(mul == x){
return (int)mid;
} else if(mul < x) {
left = (int)mid+1;
} else {
right = (int)mid-1;
}
}
return right;
}
}
package Level4;
/**
* Sqrt(x)
*
* Implement int sqrt(int x).
*
* Compute and return the square root of x.
*
*/
public class S69 {
public static void main(String[] args) {
System.out.println(sqrt(2));
}
public static int sqrt(int x) {
double diff = 0.01; // 误差
int low = 0;
int high = x;
while(low <= high){
// 注意越界!所以用double来存
double mid = low + (high-low)/2;
if(Math.abs(mid*mid-x) <= diff){
return (int)mid;
}else if(x > mid*mid+diff){
low = (int)mid+1;
}else if(x < mid*mid-diff){
high = (int)mid-1;
}
}
// 当找不到时候,这是low,high指针已经交叉,取较小的,即high
return high;
}
}
public class Solution {
public int sqrt(int x) {
int left = 0, right = x;
while(left <= right) {
double mid = left + (right-left)/2;
double mul = mid * mid;
if(mul == x){
return (int)mid;
} else if(mul < x) {
left = (int)mid+1;
} else {
right = (int)mid-1;
}
}
return right;
}
}
相关文章推荐
- 全排列——内容整理
- 实验 4 在分支循环结构中调用自定义函数
- 程序员必须知道的英语!!
- BIOS和CMOS的联系与区别
- Tomcat密码问题
- C#实现因式分解代码
- 嵌入式面试资料
- 引用 模块编译Makefile模板
- linux下I2C驱动
- osgearth earth文件规范-符号参考
- 0<Double.MIN_VALUE
- 引用 xp系统引导修复(转载)
- JAVA中sleep()、wait()、yield()、join()方法浅析
- 【引用】Linux 内核驱动--多点触摸接口
- 您可能感兴趣的100个网站 按SogouRank排序
- 科研人员常用的十八大学术搜索引擎
- c语言指针数组与数组指针
- 多线程编程技术
- 德国波恩出差记(四)
- Extjs 多表头插件GroupHeaderGrid