Menu Sidebar
Menu

bit manitupulation

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; […]

[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 […]

书脊

这青苔碧瓦堆, 俺曾睡风流觉, 将五十年兴亡看饱.

February 2023
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728