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)