LeetCode 367. Valid Perfect Square

LC address: https://leetcode.com/problems/valid-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

Analysis:

普遍能想到的是O(n)的做法,或者利用binary做O(logn)的做法。推荐大家看一下这个博客,里面有更多的解法,有些还比较有意思。

solution:

public class Solution {
    public boolean isPerfectSquare(int num) {
        int end = Math.min(46340, num);
        int start = 1;
        while (start  mid * mid) {
                start = mid + 1;
            } else {
                end = mid;
            }
        }
        return num == start * start;
    }
}

Solution code can also be found here: https://github.com/all4win/LeetCode.git

One comment

Leave a comment