目录
1、交换两个变量的值。(使用位运算)
这里用的是按位异或(^):两个操作数相同,结果为0;两个操作数结果不同,结果为1。
代码如下:
public class Test2 {
public static void main(String[] args) {
//交换两个变量的值。(使用位运算)
int i1=3;//0011
int i2=5;//0101
i1 = i1 ^ i2;//0110(6)
i2 = i1 ^ i2;//0110 ^ 0101--->0011(3)
i1 = i1 ^ i2;//0110 ^ 0011--->0101(5)
System.out.println("i1:"+i1+" i2:"+i2);
//定义第三个变量
// int temp=0;
// temp=i1;
// i1=i2;
// i2=temp;
// System.out.println("i1:"+i1+" i2:"+i2);
}
2、用三目运算符比较三个数的大小
了解三目运算:
条件?表达式1:表达式2;
(1)首先对条件进行判断,结果是布尔值;
(2)如果为true,则返回表达式1的值;
(3) 如果为false,则返回表达式2的值;
代码如下:
package com.mmx.test0830;
public class Test2 {
public static void main(String[] args) {
//用三目运算符比较三个数的大小
int a=3;
int b=4;
int c=5;
int res;
int res = a > b ? (a > c ? a : c) : (b > c ? b : c);
System.out.println(res);
}
}
3、判断奇偶数(使用位运算)
按位与(&):两个操作数都是1,结果才是1。
//判断奇偶数(使用位运算)
int i3=3;// 0011
int i4=4;// 0100
// if(i%2==1) {
// System.out.println("奇数");
// }else {
// System.out.println("偶数");
// }
//0011
// &
//0001
//0001--->1
if((i3 & 1)==0) {
System.out.println("偶数");
}else {
System.out.println("奇数");
}
//0100
// &
//0001
//0000--->0
if((i4 & 1)==1) {
System.out.println("奇数");
}else {
System.out.println("偶数");
}