[LeetCode By Go 89]367. 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

解题思路

  1. 从1~num中找平方等于num的值i,找到返回true
  2. 如果i2大于num,说明num不是平方数,返回false

代码

func isPerfectSquare(num int) bool {
    
    for i := 1; i <= num; i++ {
        if num == i * i {
            return true 
        } else if num < i * i {
            return false 
        }
    } 
    
    return false 
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/3d9b09da0696
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞