首页 > 代码库 > [leetcode] 69 Sqrt(x)
[leetcode] 69 Sqrt(x)
问题描述:
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; }
[leetcode] 69 Sqrt(x)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。