Search code examples
javabit-manipulationbitwise-operatorsbitbitwise-and

Why Bitwise AND operation not working for Value>=8?


This program is to check whether a given number is a power of 2. This code works properly till n=7 and it gives irrelevant output for input n<=8.

Input n = 4; Output : 0 ; Expected output : 0

Input : n = 8; Output: 104; Expected output : 0

 public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    String s = Integer.toBinaryString(n);
    String s2 = Integer.toBinaryString(n-1);
    Integer i = Integer.parseInt(s);
    Integer j = Integer.parseInt(s2);
    System.out.println(i&j);
    input.close();
}

Solution

  • By calls of toBinaryString and parseInt you distort the number by converting it to binary, and then interpreting the binary as decimal. Just skip this:

     public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        System.out.println(n&(n-1));
        input.close();
    }