-
Notifications
You must be signed in to change notification settings - Fork 2
/
Power of 2
57 lines (36 loc) · 1.05 KB
/
Power of 2
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
PROBLEM:-
Given a positive integer N. The task is to check if N is a power of 2. More formally, check if N can be expressed as 2x for some x.
Example 1:
Input: N = 1
Output: true
Explanation: 1 is equal to 2 raised to 0 (20 == 1).
Example 2:
Input: N = 98
Output: false
Explanation:
98 cannot be obtained by any power of 2.
Your Task: Your task is to complete the function isPowerofTwo() which takes n as a parameter and returns true or false by checking is given number can be represented as a power of two or not.
Expected Time Complexity: O(log N).
Expected Auxiliary Space: O(1).
Constraints:
0 <= N <= 1018
SOLUTION:-
JAVA CODE:
//User function Template for Java
class PowerCheck{
// Function to check if given number is power of two
public static boolean isPowerofTwo(long n){
// Your code here
if(n==0)
{
return false;
}
while(n!=1)
{
if(n%2!=0)
return false;
n=n/2;
}
return true;
}
}