当前位置:   article > 正文

[leetcode] 69 Sqrt(x)_myjayus_

myjayus_

问题描述:

Implement int sqrt(int x).

Compute and return the square root of x.

基本思路:

采用二分查找法; 犹豫输入x是int型 ,int最大范围是2147483647 ,所以返回结果的范围0-46340. 注意要根据确定的区间去查找正确的返回值,如果大于46340的数的平方将超出int的表示范围。

代码:

  1. int sqrt(int x) {
  2. if(x==0||x==1)
  3. return x;
  4. if(x >=2147395600)
  5. return 46340;
  6. int high = 46339*2-1;
  7. int low = 1;
  8. while(low <= high){
  9. int mid = (high+low)/2;
  10. int hpow = (mid+1)*(mid+1);
  11. int lpow = mid*mid;
  12. if(x>=lpow && x<hpow)
  13. return mid;
  14. else if(x<lpow)
  15. high = mid-1;
  16. else
  17. low = mid+1;
  18. }
  19. }


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. 

  1. public int sqrt(int x) {
  2. if(x==0)
  3. return 0;
  4. int h=0;
  5. while((long)(1<<h)*(long)(1<<h)<=x) // firstly, find the most significant bit
  6. h++;
  7. h--;
  8. int b=h-1;
  9. int res=(1<<h);
  10. while(b>=0){ // find the remaining bits
  11. if((long)(res | (1<<b))*(long)(res |(1<<b))<=x)
  12. res|=(1<<b);
  13. b--;
  14. }
  15. return res;
  16. }



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/164745
推荐阅读
相关标签
  

闽ICP备14008679号