Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

367. Valid Perfect Square #151

Open
Tcdian opened this issue May 9, 2020 · 1 comment
Open

367. Valid Perfect Square #151

Tcdian opened this issue May 9, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 9, 2020

367. Valid Perfect Square

给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。

说明:不要使用任何内置的库函数,如  sqrt

Example 1

Input: 16
Output: true

Example 2

Input: 8
Input: 14
Output: false
@Tcdian
Copy link
Owner Author

Tcdian commented May 9, 2020

Solution

  • JavaScript Solution
/**
 * @param {number} num
 * @return {boolean}
 */
var isPerfectSquare = function(num) {
    let left = 0;
    let right = num;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (mid * mid === num) {
            return true;
        } else if (mid * mid < num) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return false;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant