Leetcode - Number of Longest Increasing Subsequence
Leetcode - Greatest Sum Divisible by Three

Leetcode - Valid Perfect Square

violet posted @ May 10, 2020 12:16:14 AM in 算法 with tags Algorithm Golang BinarySearch , 249 阅读

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
Output: true

Example 2:

Input: 14
Output: false

 

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

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter