/website/content/ChapterFour/0069.Sqrtx.md

https://github.com/halfrost/LeetCode-Go · Markdown · 91 lines · 66 code · 25 blank · 0 comment · 0 complexity · 3c16b386877f1a69d9c9df77d0065d94 MD5 · raw file

  1. # [69. Sqrt(x)](https://leetcode.com/problems/sqrtx/)
  2. ## 题目
  3. Implement `int sqrt(int x)`.
  4. Compute and return the square root of *x*, where *x* is guaranteed to be a non-negative integer.
  5. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
  6. **Example 1**:
  7. Input: 4
  8. Output: 2
  9. **Example 2**:
  10. Input: 8
  11. Output: 2
  12. Explanation: The square root of 8 is 2.82842..., and since
  13. the decimal part is truncated, 2 is returned.
  14. ## 题目大意
  15. 实现 int sqrt(int x) 函数计算并返回 x 的平方根其中 x 是非负整数由于返回类型是整数结果只保留整数的部分小数部分将被舍去
  16. ## 解题思路
  17. - 题目要求求出根号 x
  18. - 根据题意根号 x 的取值范围一定在 `[0,x]` 之间这个区间内的值是递增有序的有边界的可以用下标访问的满足这三点正好也就满足了二分搜索的 3 大条件所以解题思路一二分搜索
  19. - 解题思路二牛顿迭代法求根号 x即求满足 `x^2 - n = 0` 方程的所有解
  20. ![](https://img-blog.csdn.net/20171019164040871?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY2hlbnJlbnhpYW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
  21. ## 代码
  22. ```go
  23. package leetcode
  24. // 解法一 二分
  25. func mySqrt(x int) int {
  26. if x == 0 {
  27. return 0
  28. }
  29. left, right, res := 1, x, 0
  30. for left <= right {
  31. mid := left + ((right - left) >> 1)
  32. if mid < x/mid {
  33. left = mid + 1
  34. res = mid
  35. } else if mid == x/mid {
  36. return mid
  37. } else {
  38. right = mid - 1
  39. }
  40. }
  41. return res
  42. }
  43. // 解法二 牛顿迭代法 https://en.wikipedia.org/wiki/Integer_square_root
  44. func mySqrt1(x int) int {
  45. r := x
  46. for r*r > x {
  47. r = (r + x/r) / 2
  48. }
  49. return r
  50. }
  51. // 解法三 Quake III 游戏引擎中有一种比 STL 的 sqrt 快 4 倍的实现 https://en.wikipedia.org/wiki/Fast_inverse_square_root
  52. // float Q_rsqrt( float number )
  53. // {
  54. // long i;
  55. // float x2, y;
  56. // const float threehalfs = 1.5F;
  57. // x2 = number * 0.5F;
  58. // y = number;
  59. // i = * ( long * ) &y; // evil floating point bit level hacking
  60. // i = 0x5f3759df - ( i >> 1 ); // what the fuck?
  61. // y = * ( float * ) &i;
  62. // y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  63. // // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
  64. // return y;
  65. // }
  66. ```