Showing posts with label Invert bits of a number. Show all posts
Showing posts with label Invert bits of a number. Show all posts

Invert bits of a number

Given a non-negative integer n. The problem is to invert the bits of n and print the number obtained after inverting the bits. Note that the actual binary representation of the number is being considered for inverting the bits, no leading 0’s are being considered.


Input : 11
Output : 4
(11)10 = (1011)[2]
After inverting the bits, we get:
(0100)2 = (4)10.

Input : 10
Output : 5
(10)10 = (1010)2.
After reversing the bits we get:
(0101)2 = (101)2
        = (5)10.



INPUT:



import java.util.Scanner;

public class InvertNumberBit {

 public static void main(String[] args) {
  
  Scanner s = new Scanner(System. in);
  String str = "";
  int n = s.nextInt();
  s.close();
        while(n > 0)
        {
            int a = n % 2;
            str = (a == 1) ? 0 + str : 1 + str;
            n = n / 2;
        }
        n = Integer.parseInt(str, 2);
        System.out.println(n);
 }
}

OUTPUT:


11
4