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
Ideas of solution
It’s not hard to see that a perfect square can be obtained by adding an odd number.That means for example, 1 plus 3 plus 5 plus 7 is 16, which is a perfect square.So we just have to think about whether a perfect square can be completely subtracted from an odd number and get to 0.If you get something other than 0, false is returned. The time complexity is O(n), and the space complexity is O(1). The time consumption is 1.9Mb.
Code
func isPerfectSquare(num int) bool {
num1 := 1
for num > 0 {
num -= num1
num1 += 2
}
if num == 0 {
return true
}else{
return false
}
}
链接:https://leetcode-cn.com/problems/valid-perfect-square/solution/shu-xue-si-lu-by-lyai-bian-cheng/
来源:力扣(LeetCode)