Skip to content

Latest commit

 

History

History
18 lines (18 loc) · 568 Bytes

367.md

File metadata and controls

18 lines (18 loc) · 568 Bytes

二分查找,用了magic num防止溢出 这题也可以牛顿切线或者O(1)的那个奇怪游戏中的算法 https://www.wikiwand.com/en/Fast_inverse_square_root

class Solution {
public:
    bool isPerfectSquare(int num) {
        int left = 1, right = min(num>>1, 46340);   //sqrt(2147483647),  avoid overflow
        while(left<right){
            int mid = (left+right) >> 1;
            if(mid*mid > num) right = mid-1;
            else if(mid*mid < num) left = mid+1;
            else return true;
        }
        return left*left == num;
    }
};