while (n != 0) {
System.out.print(n & 1);
n = n >> 1;
}
The above code in Java leads to an infinite loop, if n = -1.
How do I get it to print negative integers?
The >>
operator is a "sign-extended" right-shift operator, which means that if the top bit in the original value is set, the bits that are "shifted in" are 1. That keeps the sign of the result the same, basically.
You want the >>>
operator (the unsigned right shift operator), which always "shifts in" 0 bits, even if the top bit was 1.
See JLS section 15.19 or the Java tutorial for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With