0

I need help writing a method that takes an int num and returns the two's complement of num as an int using bitwise operators in Java.

public int twosComplement(int num) {
}

I am able to write a method using strings and "Integer.toBinaryString" and "Integer.parseInt" but I am not able to use bitwise operators since when I use "Integer.toBinaryString" for a negative num, the resulting string is too long for "Integer.parseInt" and I get an exception:

Exception in thread "main" java.lang.NumberFormatException: For input
string: "1111111111111100000001111111111111111111110000000"

    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
Gauravsa
  • 6,330
  • 2
  • 21
  • 30
M.Ruz
  • 11
  • 2

1 Answers1

0

The main reason most probably is that Integer.ParseInt without a radix treats a string as a decimal number. So, your "111,000,101,010,000" is treated in billions (or whatever)..

Need to pass in the 2 for binary.

int value = Integer.parseInt(binaryGuy, 2);

However, need to be careful for Integer.MAX_VALUE if the sign bit is set (i.e. negative number) or can use Long.parseLong or BigInteger (String s, int radix)

Gauravsa
  • 6,330
  • 2
  • 21
  • 30
  • If num = 56 I want to return value = 111000 but Integer.parseInt(binaryGuy, 2) returns 56. Both Integer.parseInt and Long.parseLong don't work for the binary representation of negative numbers and BigInteger does but it doesn't seem to work for bitwise operators. – M.Ruz Nov 08 '18 at 06:25