Menu

## Missing Number 位运算

public int missingNumber(int[] nums) { if(nums.length == 0 || nums == null) return 0; int missing = 0; for(int i = 0; i <= nums.length; i++) missing ^= i; for(int i = 0 ; i < nums.length; i++) { missing ^= nums[i]; } return missing; }

## [LintCode] Find the Missing Number

public int findMissing(int[] nums) { // write your code here if(nums.length == 0 || nums == null) return 0; int missing = 0; int n = nums.length; for(int i = 0; i <= n; i++) { missing^=i; } // xor [0,n] for(int i : nums) missi raneng ^= i;//xor i, i in nums return missing; […]

## [LintCode] Count 1 in Binary

public int countOnes(int num) { // write your code here int res = 0; for(int i = 0 ; i < 32; i++) { if((num & (1<<i)) != 0) res++; } return res; }

## [Amazon] Add Binary Number By 1 without using + 正数加1不用加号

Bit操作的题, 给一个整数+1,不能用加号. 其实很简单,扫一下整数的每个bit(从低位到高位), 对它做&操作, 如果结果是0, 证明此位是0, 那么我们在这位+1, 如果是1, 那么我们清空此位. public class addBinaryNumberBy1WithoutPlus { public int add(int n) { for(int i = 0; i < 32; i++) { if (((1 << i) & n) == 0){ //until we find the first 1 bit n = n | (1 << i); break; } else n = n […]