Question

I am trying to make a program to calculate 1's complement after entering a binary number. This is what I have to far:

import java.util.Scanner;
public class BitWiseComplement {
    public static void main(String[] args) {
        Scanner keysIn = new Scanner(System.in);
        System.out.println("Please enter your number: ");
        long originalNum = keysIn.nextLong();
        System.out.println(~originalNum);
  }
}

However, when I enter 0111011, I get -111012. I thought the ~ operator was supposed to invert the number so that all 0s are 1s and all 1s are 0s.

Any help?

Was it helpful?

Solution

You presumably want to work in binary, so try:

Scanner keysIn = new Scanner(System.in);
System.out.print("Please enter your number: ");

long originalNum = keysIn.nextLong(2);  // specify radix of 2
System.out.println(Long.toBinaryString(~originalNum));  // print binary string

keysIn.close();
Please enter your number: 0111011
1111111111111111111111111111111111111111111111111111111111000100

As you can see, all bits are flipped. Bear in mind that there are leading 0s in front of the binary number you entered.

OTHER TIPS

The ~ operator does what you think, but keep in mind that there are no unsigned types in Java, so when you enter a positive number (i.e., the high bit is a 0), applying ~ to it will make it negative (by turning the high bit on).

If you were to print the number out in hex (or binary, as other answers have suggested), you should see the answer you expect.

  • count the number of bits in num.
  • make a mask of 1s of the same length.
  • xor with the number to get the complement.

eg. 9^15=6 enter image description here

  public static int solution(int num) {

    int bits = Integer.toBinaryString(num).length();
    int maxBound = (int)( Math.pow(2, bits)-1);
    return num ^ maxBound;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top