forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
check_whether_a_number_is_power_of_2.java
60 lines (51 loc) · 1.26 KB
/
check_whether_a_number_is_power_of_2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Given a number , check whether the number is power of 2 or not.
We can check this by doing some bitwise operation.
Bitwise operations are best because they perform the operation in least possible time.
*/
import java.util.*;
import java.lang.*;
public class Powerof2
{
// This function will tell us whether a number is power of 2
static boolean number_is_power_of_2(int number)
{
/* if bitwise and of number and number-1 is zero
then we can say that number is power of 2
otherwise it is not. */
if((number & (number - 1)) == 0)
{
return true;
}
return false;
}
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number \n");
int number = scan.nextInt();
scan.close();
// Calling the number_is_power_of_2 function
boolean result = number_is_power_of_2(number);
if(result)
{
System.out.println("The Number is power of 2\n");
}
// else that number is not power of 2
else
{
System.out.println("No. the number is not power of 2\n");
}
}
}
/*
Standard Input and Output
Enter the number
64
The Number is power of 2
Enter the number
34
No. the number is not power of 2
Time Complexity : O(1)
Space Complexity : O(1)
*/