-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToggleKthBit.java
More file actions
54 lines (31 loc) · 976 Bytes
/
Copy pathToggleKthBit.java
File metadata and controls
54 lines (31 loc) · 976 Bytes
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
/*
Toggling k-th bit of a number
Ref : https://www.geeksforgeeks.org/toggling-k-th-bit-number/
For a given number n, if k-th bit is 0, then toggle it to 1 and if it is 1 then, toggle it to 0.
Input : n = 6, k = 1
Output : 7
6 is represented as 110 in binary and has its first bit 0, so toggling it will result in 111 i.e. 7.
Method :
n = 6 => 110
k = 1 => 1 << (k-1), 001
n ^ ( 1<<(k-1)) => 110
^ 001
-----------
111 => 7
------------
TC = O(1)
SC = O(1)
*/
import java.io.*;
import java.util.*;
public class ToggleKthBit{
public static int ToggleKthBitInGivenNumber(int n, int k){
return n ^ (1 << (k-1));
}
public static void main(String[] args){
int n = 6;
int k = 1 ;
System.out.println("Kth bit Toggle number = " +ToggleKthBitInGivenNumber(n,k));
}
}
//o/p:- Kth bit Toggle number = 7