Java中"与"、"或"、"非"、"异或"
文章目录
& 按位"与"操作符
public class Demo {
public static void main(String[] args) {
// &操作符
int a = 16;
//16转换为二进制为10000
int b = 17;
//17转换为二进制为10001
// 两个操作数都为1时才为1
// 10000
// & 10001
//--------------
// 10000
System.out.println(a&b);
//输出为16
}
}\| 按位"或"操作符
public class Demo {
public static void main(String[] args) {
// |操作符 int a = 16;
//16转换为二进制为10000
int b = 17;
//17转换为二进制为10001
// 两个操作数只要有一个1就为1
// 10000
// | 10001
//--------------
// 10001
System.out.println(a|b);
//输出为17
}
}~ "取反"操作符
public class Demo {
public static void main(String[] args) {
// ^操作符
int a = 8;
int b = 9;
//8转换为二进制为1000
//9转换为二进制为1001
// 异或规则相同为0不同为1
// 1000
// | 1001
//--------------
// 0001
System.out.println(a^b);
//输出为1
}
}假如有一个数组中有两个相同的内容只有一个是不一样的,那么如何找到这个不一样的数。
<span class="colour" style="color:rgb(51, 51, 51)">可能我叙述的不太容易理解,假如我们有以下数组。</span>
int temp = {1,2,3,4,5,4,3,2,1};<span class="colour" style="color:rgb(51, 51, 51)">可以看到数组中的1、2、3、4都是有两个,但是只有5有一个,而我们要做的就是找到这个5。</span>
<span class="colour" style="color:rgb(51, 51, 51)">如何用十分简洁的代码就可以实现这个功能呢?</span>
<span class="colour" style="color:rgb(51, 51, 51)">这里使用了一个异或的特性。</span>
public class Demo {
public static void main(String[] args) {
int[] temp = {1,2,5,2,1,4,4,15,5};
int a = 0;
for(int i=0;i<temp.length;i++) {
a = a ^ temp[i];
}
System.out.println(a);
}
}<span class="colour" style="color:rgb(51, 51, 51)">运行这段代码。</span>
C:\Users\PiLiPaLa\Desktop\Code\Eight>java Demo
15<span class="colour" style="color:rgb(51, 51, 51)">成功的将15输出了。</span>
<span class="colour" style="color:rgb(51, 51, 51)">其实原理就是异或,有两个相同的数就会抵消变成0,然后只剩下单独的那一个。</span>
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论