当前位置:   article > 正文

leetcode_78 Sqrt(x)

leetcode_78 Sqrt(x)

题目:

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.

本文采用binary search

代码如下:

  1. class Solution {
  2. public:
  3. int mySqrt(int x) {
  4. if(x == 0)
  5. return 0;
  6. int left = 1, right = x;
  7. while(left <= right)
  8. {
  9. int mid = left + (right - left)/2;
  10. if(mid == x/mid)
  11. {
  12. return mid;
  13. }
  14. else if(mid > x / mid)
  15. {
  16. right = mid - 1;
  17. }
  18. else
  19. {
  20. left = mid + 1;
  21. }
  22. }
  23. return right;
  24. }
  25. };

 

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

闽ICP备14008679号