美文网首页
多个数的异或

多个数的异或

作者: 小五_555 | 来源:发表于2016-08-02 16:09 被阅读0次

走在路上,太阳太烈。突然想到个问题,异或的结果跟顺序有关吗?
对于异或来说, 一般教科书的解释是两个数相同则为0,不同则为1。
来点以前做硬件时候的感想,半加法器是由异或和与门来搭建的, 异或逻辑作为本位,与门作为进位。这样呢,可以感性地理解一些问题,来点小学的数学,加法的结果跟顺序是无关的,所以异或的结果跟顺序是无关的。
这里,做点简单的测试,一段java代码。
permutation 是通过dfs生成所有的组合。
hasEqualXorRequest 返回所有组合的异或值是不是相同。


public class TestXor {
 
 public ArrayList<ArrayList<Integer>> permutation(ArrayList<Integer> array){
  ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
  ArrayList<Integer> path = new ArrayList<Integer>();
  dfs(array, path, res);
  return res;
  
 }
 
 public void dfs(ArrayList<Integer> A, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> res){
  if(path.size() == A.size()){
   res.add(new ArrayList<Integer>(path));
  }
  for(int i: A){
   if(path.contains(i)){
    continue;
   }
   path.add(i);
   this.dfs(A, path, res);
   path.remove(path.size() - 1);
  }
 }
 
 
 public int getXorSingle(ArrayList<Integer> sample){
  int i = 0;
  for(int x: sample){
   i = i ^ x;
  }
  return i;
 }
 
 public boolean hasEqualXorRequest(ArrayList<ArrayList<Integer>> samples){
  if(samples.size() <= 1){
   return true;
  }
  int xorResult = this.getXorSingle(samples.get(0));
  for(ArrayList<Integer> sample: samples){
   if(this.getXorSingle(sample) != xorResult){
    return false;
   }
  }
  return true;
 }
 
 public static void main(String[] args) {
  TestXor tx = new TestXor();
  ArrayList<Integer> array = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
  ArrayList<ArrayList<Integer>> res = tx.permutation(array);
  System.out.println(res.size());
  System.out.println(res);
  System.out.print(tx.hasEqualXorRequest(res));
 }
}

相关文章

  • 多个数的异或

    走在路上,太阳太烈。突然想到个问题,异或的结果跟顺序有关吗?对于异或来说, 一般教科书的解释是两个数相同则为0,不...

  • lintcode Flip Bits

    看异或之后1的个数

  • 面试题40:数组中只出现一次的数字

    这一题最关键的点在于,使用异或之后得到的是两个数的异或结果,如何区分开这两个数呢?答案是,根据异或结果的一个为1的...

  • 位运算

    异或。 异或的规则。 2.常见的的操作 3.复杂的操作 例题 数字中1的个数

  • 异或加密解密

    异或,英文为exclusive OR,或缩写成xor异或(xor)是一个数学运算符。它应用于逻辑运算。异或的数学符...

  • 汇编 进制练习

    加密:对一个数进行异或的结果再进行异或会得到最开始的数据。这就是加密的本质。秘钥是进行异或的数,原始数据是被异或的...

  • 数组中出现次数为1(有两个)的数字

    思路:(1)一个数字异或它本身等于0,所以如果一个数组中只存在一个出现一次的数字,那么这个数组所有的元素异或,就是...

  • 子数组的最大异或和

    一,题目描述 给定一个数组,求子数组的最大异或和。一个数组的异或和为,数组中所有的数异或起来的结果 二,一般算法分...

  • 位操作的常见算法

    一、异或^1、交换两个数:'''cvoid Swap(int &a, int &b){if (a != b){a ...

  • LeetCode 268. Missing Number

    三种方法1、异或操作。因为两个相同的数异或之后等于零,所以将数组与0到n异或,最后剩下的那个数就是数组中缺失的数。...

网友评论

      本文标题:多个数的异或

      本文链接:https://www.haomeiwen.com/subject/ffnfsttx.html