异或应用
来源:互联网 发布:淘宝店铺质检报告没有 编辑:程序博客网 时间:2024/06/05 02:17
1. 给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符 (异或又名: 不进位加法)
a + b = (a ^ b) + (a & b << 1)
2. 数组中,只有一个数出现一次,剩下都出现两次,找出出现一次的数
public class Solution { public int singleNumber(int[] nums) { int result = 0, n = nums.length; for (int i = 0; i < n; i++) { result ^= nums[i]; } return result; }}
3. 数组中,只有一个数出现一次,剩下都出现三次,找出出现一次的数
Ones,Twos俩个数表示当前位的状态
如果Twos里面ith是1,则ith当前为止出现1的次数除以3的状态是2
如果Ones里面ith是1,则ith目前为止出现1的次数除以3的状态是1
public class Solution { public int singleNumber(int[] nums) { int ones = 0, twos = 0; for(int i = 0; i < nums.length; i++){ ones = (ones ^ nums[i]) & ~twos; twos = (twos ^ nums[i]) & ~ones; } return ones; }}
设此两个数为x和y,对于x和y,一定是其中一个这一位是1,另一个这一位不是1。对于其他成对出现的元素,要么都在x所在的那个集合,要么在y所在的那个集合。
public class Solution { public int[] singleNumber(int[] nums) { //用于记录,区分“两个”数组 int diff = 0; for(int i = 0; i < nums.length; i ++) { diff ^= nums[i]; } //diff & (-diff)就是取diff的最后一位1的位置 diff &= -diff; int[] rets = {0, 0}; for(int i = 0; i < nums.length; i ++) { //分属两个“不同”的数组 if ((nums[i] & diff) == 0) { rets[0] ^= nums[i]; } else { rets[1] ^= nums[i]; } } return rets; }}5. Maximum XOR of Two Numbers in an Array
int findMaximumXOR(vector<int>& nums) { int max = 0, mask = 0; unordered_set<int> t; // search from left to right, find out for each bit is there // two numbers that has different value for (int i = 31; i >= 0; i--){ // mask contains the bits considered so far mask |= (1 << i); t.clear(); // store prefix of all number with right i bits discarded for (int n: nums){ t.insert(mask & n); } // now find out if there are two prefix with different i-th bit // if there is, the new max should be current max with one 1 bit at i-th position, which is candidate // and the two prefix, say A and B, satisfies: // A ^ B = candidate // so we also have A ^ candidate = B or B ^ candidate = A // thus we can use this method to find out if such A and B exists in the set int candidate = max | (1<<i); for (int prefix : t){ if (t.find(prefix ^ candidate) != t.end()){ max = candidate; break; } } } return max; }Sample:
'000010001000211001000
1100
0100
001111001100111101010
1110
0110
001011101100011111010
1111
0110
001111011100
阅读全文
0 0
- 异或运算应用
- 异或运算应用
- 异或的应用
- 异或应用
- 异或操作的应用
- 异或的性质&应用
- 异或的巧妙应用
- 异或运算及其应用
- 异或理解与应用
- 异或运算及其应用
- 异或运算及其应用
- 异或运算及其应用
- 异或运算及其应用
- Java学习-异或应用
- 异或^运算的应用
- 异或应用小总结
- 异或运算及其应用
- 异或、异或和 的性质与应用
- Socket
- 细说mysql索引
- Integer与int的比较
- 分库、分表、集群、负载均衡
- Jenkins中Git Timeout错误
- 异或应用
- Spring常用注解总结
- 企业证书打包ipa文件(图文详解)
- Vue学习之源码分析--从template到DOM(Vue.js源码角度看内部运行机制)(九)
- Python 读写excel
- iOS开发之Xcode9报错 Compiling IB documents for earlier than iOS7 is no longer supported.
- kernel struct file结构中的private_data
- android:layout_weight的真实含义
- Hibernate