-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClearKthBit.java
More file actions
60 lines (34 loc) · 1.03 KB
/
Copy pathClearKthBit.java
File metadata and controls
60 lines (34 loc) · 1.03 KB
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
/*
Program to clear K-th bit of a number N
Given a number N, the task is to clear the K-th bit of this number N.
If K-th bit is 1, then clear it to 0 and if it is 0 then leave it unchanged.
Input: N = 5, K = 1
Output: 4
5 is represented as 101 in binary
and has its first bit 1, so clearing
it will result in 100 i.e. 4.
Method:-
Since bitwise AND of any bit with a reset bit results in a reset bit, i.e.
n = 5 , k =1
5 = 101 , 1<<k-1 = 1 << 0 = 001 , ~ (001) = 110
101
(AND) 110
-------------------------
100 4
-------------------------
TC = O(1)
SC = O(1)
*/
import java.io.*;
import java.util.*;
public class ClearKthBit{
public static int ClearKthBitInGivenNumber(int n, int k){
return n & ~(1 << (k-1));
}
public static void main(String[] args){
int n = 5;
int k = 1 ;
System.out.println("Kth bit Clear number = " +ClearKthBitInGivenNumber(n,k));
}
}
//o/p:- Kth bit Clear number = 4