zoukankan      html  css  js  c++  java
  • [LeetCode] Sqrt(x)

     

    Implement int sqrt(int x).

    Compute and return the square root of x.

    x is guaranteed to be a non-negative integer.


    Example 1:

    Input: 4
    Output: 2
    

    Example 2:

    Input: 8
    Output: 2
    Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

    编写Sqrt(x)函数

    使用二分搜索来查值进行平分计算。

    class Solution {
    public:
        int mySqrt(int x) {
            int left = 0, right = x;
            while (left <= right) {
                long long mid = left + (right - left) / 2;
                if (pow(mid, 2) > x) {
                    right = mid - 1;
                }
                else {
                    if (pow(mid + 1, 2) > x)
                        return mid;
                    left = mid + 1;
                }
            }
        }
    };
    // 22 ms
  • 相关阅读:
    uva-321-暴力枚举-隐式图搜索
    uva-704-暴力枚举-双向bfs
    整数的无符号编码和有符号编码
    HDU 5793
    HDU 5730
    HDU 5740
    HDU 5768
    HDU 1194
    HDU 1086
    HDU 5145
  • 原文地址:https://www.cnblogs.com/immjc/p/8075059.html
Copyright © 2011-2022 走看看