LeetCode 69. Sqrt(x)(x的算術平方根)
阿新 • • 發佈:2019-02-11
題目描述:
Implement int sqrt(int x)
.
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
例子:
Input: 4 Output: 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.
分析:
題意:給定一個非負整型數x,返回x的算術平方根。
時間複雜度為O(log(x))。
程式碼:
#include <bits/stdc++.h> using namespace std; #define LL long long class Solution { public: int mySqrt(int x) { // Exceptional Case: if(x <= 1){ return x; } int left = 1, right = x; while(left <= right){ int mid = left + (right - left) / 2; if((LL)mid * (LL)mid == (LL)x){ return mid; } else if((LL)mid * (LL)mid > (LL)x){ right = mid - 1; } else if((LL)mid * (LL)mid < (LL)x){ left = mid + 1; } } return right; } };