LeetCode - 191. Number of 1 Bits
2016-07-03 11:51
295 查看
求出一个无符号数二进制表示中1的个数,这个题目首先想到的是将给出的数字变成二进制表示,并且每看到一个1,就将numberOfOne的数量加一。但是这种方法错误的,错误的原因就在于没有考虑题目中给出的无符号数的这个特性,原来循环中的写法是:
if(n % 2 == 0) result++;
n /= 2
但这样是不对的,对于LeetCode上给出的测试用例0b10000000000000000000000000000000,这种写法无法通过,因为编译器会把这个数的最高一位当作符号位来看,故而只能通过二进制移位的方法来判断。注意Java中对于移位有两套运算符,>> 1表示右移一位,相当于/ 2,这样是不行的,要使用另一种移位方法,也就是>>> 1,它是无符号移位,在移位的过程中会在高位补0。时间复杂度为O(1),因为无论数字多大,最多移动32次,空间复杂度为O(1),代码如下:
另一种方法利用了位操作的一个小技巧,通过每次寻找最低一位的1并且增加numberOfOne的数量得到答案,一个清晰的图示如下:
同样地,时间复杂度为O(1),空间复杂度为O(1),代码如下:
知识点:
1. 注意符号数和无符号数的不同
2. 注意Java中>>和>>>的区别
3. 位操作中n & (n - 1)的含义
if(n % 2 == 0) result++;
n /= 2
但这样是不对的,对于LeetCode上给出的测试用例0b10000000000000000000000000000000,这种写法无法通过,因为编译器会把这个数的最高一位当作符号位来看,故而只能通过二进制移位的方法来判断。注意Java中对于移位有两套运算符,>> 1表示右移一位,相当于/ 2,这样是不行的,要使用另一种移位方法,也就是>>> 1,它是无符号移位,在移位的过程中会在高位补0。时间复杂度为O(1),因为无论数字多大,最多移动32次,空间复杂度为O(1),代码如下:
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int result = 0; while(n != 0){ result += n & 1; n >>>= 1; } return result; } }
另一种方法利用了位操作的一个小技巧,通过每次寻找最低一位的1并且增加numberOfOne的数量得到答案,一个清晰的图示如下:
public class Solution{ public int hammingWeight(int n) { int sum = 0; while (n != 0) { sum++; n &= (n - 1); } return sum; } }
同样地,时间复杂度为O(1),空间复杂度为O(1),代码如下:
知识点:
1. 注意符号数和无符号数的不同
2. 注意Java中>>和>>>的区别
3. 位操作中n & (n - 1)的含义
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解