367. Valid Perfect Square

  • 37.8%

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.

1
2
3
4
5
> Example 1:
>
> Input: 16
> Returns: True
>
1
2
3
4
5
> Example 2:
>
> Input: 14
> Returns: False
>

java

Solution 1:

1ms, , June.28th, 2016

https://leetcode.com/discuss/110638/a-square-number-is-1-3-5-7-java-code

1
2
3
4
5
6
7
8
9
10
public class Solution {
public boolean isPerfectSquare(int num) {
int i = 1;
while(num > 0){
num -= i;
i += 2;
}
return num == 0;
}
}

cpp

Solution 1:

0ms, June.28th, 2016

https://leetcode.com/discuss/110671/3-4-short-lines-integer-newton-most-languages

https://leetcode.com/discuss/58631/3-4-short-lines-integer-newton-every-language

1
2
3
4
5
6
7
8
9
class Solution {
public:
bool isPerfectSquare(int num) {
long r = num;
while (r*r > num)
r = (r + num/r) / 2;
return r*r == num;
}
};

python

Solution 1:

48ms, June.28th, 2016

https://leetcode.com/discuss/110671/3-4-short-lines-integer-newton-most-languages

https://leetcode.com/discuss/58631/3-4-short-lines-integer-newton-every-language

1
2
3
4
5
6
7
8
9
10
class Solution(object):
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
r = num
while r*r > num:
r = (r + num/r) / 2
return r * r == num
谢谢你,可爱的朋友。