File tree Expand file tree Collapse file tree 1 file changed +28
-3
lines changed
Leetcode/Leetcode_August_Challenge Expand file tree Collapse file tree 1 file changed +28
-3
lines changed Original file line number Diff line number Diff line change 1
1
package Leetcode_August_Challenge ;
2
-
2
+ import java . util . Scanner ;
3
3
public class Day4_PowerOfFour {
4
4
5
5
public static void main (String [] args ) {
6
-
7
- int num = 64 ;
6
+ Scanner sc = new Scanner (System .in );
7
+ System .out .println ("Enter number" );
8
+ int num = sc .nextInt ();
8
9
System .out .println (isPowerOfFour (num ));
9
10
System .out .println (isPowerOfFour (5 ));
10
11
System .out .println (isPowerOfFour_log (num ));
11
12
System .out .println (isPowerOfFour_log (5 ));
13
+ System .out .println (isPowerOfFour2 (num ));
14
+ System .out .println (isPowerOfFour2 (5 ));
12
15
}
13
16
14
17
// approach 1- using loop
@@ -38,4 +41,26 @@ public static boolean isPowerOfFour_log(int num) {
38
41
// System.out.println(Math.floor(logn) + " "+ Math.ceil(logn));
39
42
return Math .floor (logn ) == Math .ceil (logn );
40
43
}
44
+
45
+ // approach 3
46
+ static boolean isPowerOfFour2 (int num ) {
47
+ int count = 0 ;
48
+
49
+ // Check if there is only one bit set in num
50
+ int x = num & (num - 1 );
51
+
52
+ if (num > 0 && x == 0 ) {
53
+ // count 0 bits before set bit
54
+ while (num > 1 ) {
55
+ num >>= 1 ;
56
+ count += 1 ;
57
+ }
58
+
59
+ // If count is even then return true else false
60
+ return (count % 2 == 0 ) ? true : false ;
61
+ }
62
+
63
+ // If there are more than 1 bit set then num is not a power of 4
64
+ return false ;
65
+ }
41
66
}
You can’t perform that action at this time.
0 commit comments