public class BitwiseExample {
public static void main(String[] args) {
int number = 5;
if ((number & 1) == 1) {
System.out.println(number + " 是奇数");
} else {
System.out.println(number + " 是偶数");
}
}
}
示例 2: 交换两个变量的值(不使用临时变量)
public class BitwiseSwap {
public static void main(String[] args) {
int a = 5, b = 10;
a = a ^ b;
b = a ^ b; // 此时b = (a^b)^b = a^(b^b) = a^0 = a,恢复a的原值
a = a ^ b; // 此时a = (a^b)^a = b^(a^a) = b^0 = b,a变为b的值
System.out.println("a = " + a + ", b = " + b);
}
}
示例 3: 快速幂运算
public class FastPower {
public static int fastPower(int base, int exponent) {
int result = 1;
while (exponent > 0) {
if ((exponent & 1) == 1) { // 如果当前位是1,则乘以base
result *= base;
}
exponent >>= 1; // 右移一位,相当于exponent除以2
base *= base; // base自乘,为下一次可能的乘法做准备
}
return result;
}
public static void main(String[] args) {
int base = 2;
int exponent = 10;
System.out.println(base + " 的 " + exponent + " 次方是 " + fastPower(base, exponent));
}
}