bit manipulation
bsbcarter
这个作者很懒,什么都没留下…
展开
-
LeetCode-Missing Number
这个题有很多方法 1.计算和 再每个减去 注意overflowpublic class Solution { public int missingNumber(int[] nums) { int n = nums.length; double sum = ( 1+n ) * n /2; for ( int i = 0; i < n; i ++原创 2015-09-18 05:54:23 · 276 阅读 · 0 评论 -
**LeetCode-Divide Two Integers
首先不看那些corner case的话 不管正负号 思想就是每次给除数乘以二 然后和被除数比较 找到最大的一个比被除数小的倍数 比如15/3 那最大的可以从15里面减去的就是12 是3的四倍 乘以二通过左移一位来实现 这样的话为了记录那个最大数字是除数的几倍 同时用一个1来同时左移记录 发现是四倍 然后就从被除数中减去这个最大倍数 然后一直循环到即使1倍也不能减去了 就累计出来了得数 但是原创 2015-11-02 01:11:46 · 203 阅读 · 0 评论 -
*LeetCode-Single Number II
这个题比较直接的想法是用一个HashMap对于出现的元素进行统计,key是元素,value是出现个数,如果元素出现三次,则从HashMap中移除,最后在HashMap剩下来的元素就是我们要求的元素(因为其他元素都出现三次,有且仅有一个元素不是如此)。这样需要对数组进行一次扫描,所以时间复杂度是O(n),而需要一个哈希表来统计元素数量,总共有(n+2)/3个元素,所以空间复杂度是O((n+2)/3)原创 2015-09-24 05:28:06 · 242 阅读 · 0 评论 -
Bit Manipulation
1. >> 和 >>> >> is arithmetic shift right, >>> is logical shift right. In an arithmetic shift, the sign bit is extended to preserve the signedness of the number. For example: -2 repres原创 2015-09-24 04:57:11 · 249 阅读 · 0 评论 -
*LeetCode-Single Number III
这个题是有两个数字出现一次 剩下的全都出现两次 方法是先找到这两个数的xor 即全都xor到一起 然后找到这个xor的最后一位置位的位置(为1 的那位) 说明这一位上 这两个数字不同 得到这个last set bit的方法是 num &= - num 一个数的complement 是-num。 一个数和它的补码and 就会得到 last set bit 然后 设置两个累加的xor 假如一原创 2015-09-24 05:49:11 · 268 阅读 · 0 评论 -
*LeetCode-Bitwise AND of Numbers Range
其实在一个range内 只要看两个边界就可以了 一定是在高位的连续几位会都相同 之后的几位会vary 后面一定会全是0 所以一直把m n右移 计数 然后知道他们完全相同 完全相同之后再后面补足之前计数的个数0 public class Solution { public int rangeBitwiseAnd(int m, int n) { int diffNum原创 2015-09-23 07:57:45 · 282 阅读 · 0 评论 -
*LeetCode-Reverse Bits
每次取最低位 加在中间结果的上面 然后把中间结果左移一位 除了最后一次不用左移 public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int res = 0; for ( int i = 1; i <= 32;原创 2015-09-23 07:18:32 · 293 阅读 · 0 评论 -
*LeetCode-Number of 1 Bits
每次把n的最后一位和1做& 假如是1 那么就累计有一位, 然后把n右移一位 注意这里右移用的是unsigned >>> 因为不要考虑最高位的sign 然后while的判断条件一定是 n != 0 In Java we need to put attention on the fact that the maximum integer is 2147483647. Integer type原创 2015-09-23 05:54:16 · 280 阅读 · 0 评论 -
LeetCode-Single Number
用抑或 两个bit 相同就返回0 不同返回1 所以a^a = 0 n ^ 0 = n public class Solution { public int singleNumber(int[] nums) { int xor = nums[0]; for ( int i = 1; i < nums.length; i ++ ){原创 2015-09-17 08:50:11 · 231 阅读 · 0 评论 -
*LeetCode-Power of Two
首先除法的要注意corner case 0,1之类的 然后就是另一个方法是数bit 1 的个数 2的power只能有一个1 public class Solution { public boolean isPowerOfTwo(int n) { return n>0 && Integer.bitCount(n) == 1; } }原创 2015-11-08 00:14:20 · 274 阅读 · 0 评论