File tree 2 files changed +73
-0
lines changed
2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ package leetcode .easy ;
2
+
3
+ public class ValidPerfectSquare {
4
+
5
+ boolean isPerfectSquareBinary (int num ) {
6
+ if (num < 0 ) return false ; // Negative numbers cannot be perfect squares
7
+ if (num == 0 || num == 1 ) return true ; // 0 and 1 are perfect squares
8
+
9
+ long left = 1 , right = num ;
10
+
11
+ while (left <= right ) {
12
+ long mid = left + (right - left ) / 2 ;
13
+ long square = mid * mid ;
14
+
15
+ if (square == num ) {
16
+ return true ; // Found the perfect square
17
+ } else if (square < num ) {
18
+ left = mid + 1 ; // Search in the right half
19
+ } else {
20
+ right = mid - 1 ; // Search in the left half
21
+ }
22
+ }
23
+
24
+ return false ; // No perfect square found
25
+ }
26
+
27
+ boolean isPerfectSquareMaths (int num ) {
28
+ int oddNumber = 1 ;
29
+ int sum = 1 ;
30
+ while (sum <= num ) {
31
+ // Found the perfect square
32
+ if (sum == num ) {
33
+ return true ;
34
+ }
35
+
36
+ oddNumber += 2 ; // Next odd number
37
+ sum += oddNumber ;
38
+ }
39
+
40
+ return false ;
41
+ }
42
+
43
+ }
Original file line number Diff line number Diff line change
1
+ package leetcode .easy ;
2
+
3
+ import org .junit .jupiter .api .Test ;
4
+
5
+ import static org .junit .jupiter .api .Assertions .*;
6
+
7
+ class ValidPerfectSquareTest {
8
+
9
+ private final ValidPerfectSquare validPerfectSquare ;
10
+
11
+ ValidPerfectSquareTest () {
12
+ validPerfectSquare = new ValidPerfectSquare ();
13
+ }
14
+
15
+ @ Test
16
+ void testIsPerfectSquareBinary () {
17
+ assertTrue (validPerfectSquare .isPerfectSquareBinary (16 ));
18
+ assertTrue (validPerfectSquare .isPerfectSquareBinary (1 ));
19
+ assertFalse (validPerfectSquare .isPerfectSquareBinary (14 ));
20
+ assertFalse (validPerfectSquare .isPerfectSquareBinary (-1 ));
21
+ }
22
+
23
+ @ Test
24
+ void testIsPerfectSquareMaths () {
25
+ assertTrue (validPerfectSquare .isPerfectSquareMaths (16 ));
26
+ assertTrue (validPerfectSquare .isPerfectSquareMaths (1 ));
27
+ assertFalse (validPerfectSquare .isPerfectSquareMaths (14 ));
28
+ assertFalse (validPerfectSquare .isPerfectSquareMaths (-1 ));
29
+ }
30
+ }
You can’t perform that action at this time.
0 commit comments