重复第3章中的练习10,不要用Integer.toBinaryString()方法,而是用三元操作符和按位操作符来显示二进制的1和0
这题比较有意思,写一下我的解法
package control;
import static java.lang.System.out;
public class Exercise5
{
static final int INT_HIGH_BIT = 1 << 31;
public static void main(String[] args) throws InterruptedException
{
int i = 0x2aa;
int j = 0x555;
out.println("i:"+toBinaryString(i));
out.println("j:"+toBinaryString(j));
out.println("~i:"+toBinaryString(~i));
out.println("~j:"+toBinaryString(~j));
out.println("(i|j):"+toBinaryString(i|j));
out.println("(i&j):"+toBinaryString(i&j));
out.println("(i^i):"+toBinaryString(i^i));
out.println("(i|j):"+toBinaryString(~(i|j)));
out.println("~(i&j):"+toBinaryString(~(i&j)));
out.println("(i^j):"+toBinaryString(i^j));
}
private static String toBinaryString(int i)
{
String result = "";
int j = 1;
do {
if (j == INT_HIGH_BIT) {
result = ((i & j) > 0 ? "0" : "1") + result;
} else {
result = ((i & j) > 0 ? "1" : "0") + result;
}
i = i - (i & j);
j <<= 1;
} while (i != 0);
return result;
}
}/*Output:
i:1010101010
j:10101010101
~i:11111111111111111111110101010101
~j:11111111111111111111101010101010
(i|j):11111111111
(i&j):0
(i^i):0
(i|j):11111111111111111111100000000000
~(i&j):11111111111111111111111111111111
(i^j):11111111111
*/