天天看點

leetcode刷題,總結,記錄,備忘 367

leetcode367Valid Perfect Square

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as 

sqrt

.

Example 1:

Input: 16
Returns: True
      

Example 2:

Input: 14
Returns: False      

根據題目提示,首先使用二分法,很好做。

class Solution {
public:
    bool isPerfectSquare(int num) {
        int low = 1;
        int high = num / 2;
        
        while (low < high)
        {
            long long mid = (low + high) / 2;
            if (mid * mid == num)
            {
                return true;
            }
            else if (mid * mid < num)
            {
                low = mid + 1;
            }
            else if (mid * mid > num)
            {
                high = mid - 1;
            }
        }
        
        if (low * low == num)
        {
            return true;
        }
        
        return false;
    }
};
           

然後看了眼讨論區,發現使用分數指數次幂的方法,求num的0.5次幂,實際上就是做了sqrt,高中數學的一些知識還是挺重要的。

class Solution {
public:
    bool isPerfectSquare(int num) {
        return (int)(pow(num, 0.5)) == pow(num, 0.5) ? true : false;
    }
};