[leetcode] 69 Sqrt(x)
来源:互联网 发布:fetchassoc php 编辑:程序博客网 时间:2024/05/22 00:23
问题描述:
Implement int sqrt(int x)
.
Compute and return the square root of x.
基本思路:
采用二分查找法; 犹豫输入x是int型 ,int最大范围是2147483647 ,所以返回结果的范围0-46340. 注意要根据确定的区间去查找正确的返回值,如果大于46340的数的平方将超出int的表示范围。
代码:
int sqrt(int x) { if(x==0||x==1) return x; if(x >=2147395600) return 46340; int high = 46339*2-1; int low = 1; while(low <= high){ int mid = (high+low)/2; int hpow = (mid+1)*(mid+1); int lpow = mid*mid; if(x>=lpow && x<hpow) return mid; else if(x<lpow) high = mid-1; else low = mid+1; } }
a better method
Since sqrt(x) is composed of binary bits, I calculate sqrt(x) by deciding every bit from the most significant to least significant.
public int sqrt(int x) { if(x==0) return 0; int h=0; while((long)(1<<h)*(long)(1<<h)<=x) // firstly, find the most significant bit h++; h--; int b=h-1; int res=(1<<h); while(b>=0){ // find the remaining bits if((long)(res | (1<<b))*(long)(res |(1<<b))<=x) res|=(1<<b); b--; } return res;}
0 0
- Leetcode 69 sqrt(x)
- leetcode 69 Sqrt(x)
- [leetcode 69] Sqrt(x)
- [leetcode] 69 Sqrt(x)
- leetcode-69 Sqrt(x)
- LeetCode 69 Sqrt(x)
- leetcode || 69、Sqrt(x)
- LeetCode 69 Sqrt(x)
- LeetCode-69 Sqrt(x)
- Sqrt(x) - LeetCode 69
- leetcode 69:Sqrt(x)
- LeetCode---(69)Sqrt(x)
- Leetcode #69 Sqrt(x)
- LeetCode(69) Sqrt(x)
- leetcode 69: Sqrt(x)
- Leetcode#69||Sqrt(x)
- [Leetcode]#69 Sqrt(x)
- 【leetcode】【69】Sqrt(x)
- 屌丝CP秘籍:各大渠道免费资源列表(完整版)
- JAVA知识点总结(五)多线程
- 如何用li标签来实现网页导航菜单
- logistic regression using Theano 注释版
- Python程序员常用的IDE和其它开发工具
- [leetcode] 69 Sqrt(x)
- Android开发之PullParser解析器用法
- 哈希_线性探测
- 浅谈五大Python Web框架
- 【摇摇开门】:管理,必须以“实用主义”为最高准则
- android ImageView实现图片浏览器(点击左侧显示上一张,点击右侧显示下一张)
- Android 反射调用方法并利用此方法展开android通知栏(兼容4.2及以上)
- 《统计学习方法》学习笔记
- 实时计算