Leecode 0367. Valid Perfect Square
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
Output: true
Example 2:
Input: 14
Output: false
完全平方数可以表示为连续奇数的和。
算法原理
该算法利用了以下数学特性:
- 1 = 1(1²)
- 1 + 3 = 4(2²)
- 1 + 3 + 5 = 9(3²)
- 1 + 3 + 5 + 7 = 16(4²)
- 以此类推,n² = 1 + 3 + 5 + ... + (2n-1)
算法通过不断从目标数中减去连续的奇数(1, 3, 5, 7...),如果最终结果恰好为 0,则说明该数是完全平方数。
1 | class Solution |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.