+ 1
Write a program to toggle a bit a position='pos' in a number "n" in java
#java
3 Answers
+ 2
Attempts?
0
Vinit Kumar. If you are unsure how to do this, here are some tips: Use the left shift operator to shift 1 into the bit position pos. Use the exclusive-or operator to toggle the bit in n.
0
public class Bit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in):
System.out.println("enter your number :"):
int n = sc.nextInt(); // The number in which you want to toggle a bit
System.out.println("enter the position:")
int pos = sc.nextInt(); // The position of the bit to toggle (0-based index)
System.out.println("Original Number: " + n);
// Create a mask with a 1 at the desired position
int mask = 1 << pos;
// Use XOR (^) to toggle the bit at the specified position
n = n ^ mask;
System.out.println("Number after toggling bit " + pos + ": " + n);
}
}