Skip to content

Latest commit

 

History

History
126 lines (95 loc) · 2.42 KB

File metadata and controls

126 lines (95 loc) · 2.42 KB

English Version

题目描述

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

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

 

示例 1:

输入:num = 16
输出:true

示例 2:

输入:num = 14
输出:false

 

提示:

  • 1 <= num <= 2^31 - 1

解法

二分法。

Python3

class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        left, right = 1, num
        while left < right:
            mid = left + ((right - left) >> 1)
            if num // mid <= mid:
                right = mid
            else:
                left = mid + 1
        return left * left == num

Java

class Solution {
    public boolean isPerfectSquare(int num) {
        int left = 1, right = num;
        while (left < right) {
            int mid = (left + right) >>> 1;
            if (num / mid <= mid) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left * left == num;
    }
}

C++

class Solution {
public:
    bool isPerfectSquare(int num) {
        long left = 1, right = num;
        while (left < right) {
            int mid = left + ((right - left) >> 1);
            if (num / mid <= mid) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left * left == num;
    }
};

Go

func isPerfectSquare(num int) bool {
	left, right := 1, num
	for left < right {
		mid := left + (right-left)>>1
		if num/mid <= mid {
			right = mid
		} else {
			left = mid + 1
		}
	}
	return left*left == num
}

...