多个数的异或

2016-08-02  本文已影响0人  小五_555

走在路上,太阳太烈。突然想到个问题,异或的结果跟顺序有关吗?
对于异或来说, 一般教科书的解释是两个数相同则为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));
 }
}
上一篇 下一篇

猜你喜欢

热点阅读