+ 1

Write a program to toggle a bit a position='pos' in a number "n" in java

#java

12th Aug 2022, 4:02 PM
Vinit Kumar.
Vinit Kumar. - avatar
3 Réponses
+ 2
Attempts?
12th Aug 2022, 5:10 PM
A͢J
A͢J - avatar
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.
12th Aug 2022, 11:12 PM
Brian
Brian - avatar
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); } }
18th Oct 2023, 9:46 AM
Yogita Kambli
Yogita Kambli - avatar