191 - Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
剑指offer上给的解法,每次&(n-1)可以将最右端的1变为0,且只会将最右端的1变为0,循环操作下去可以求出有多少个1
class Solution {
public:
int hammingWeight(uint32_t n) {
int ans = 0;
while (n) {
n &= (n - 1);
ans++;
}
return ans;
}
};
190. Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
跟上边那题思路是一样的,如果不想改变n的值的话,可以写在循环里 ((n >> i) & 1)
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
int ans = 0;
for (int i = 0; i < 32; ++i, n >>= 1) {
ans <<= 1;
ans += n & 1;
}
return ans;
}
};
338. Counting Bits
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example:
For num = 5
you should return [0,1,1,2,1,2]
.
Follow up:
- It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
- Space complexity should be O(n).
- Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
稍微有点难度?求出从0~num所有的数的二进制有多少个1,返回一个数组
本来分析了一下,是个有规律增加的情况,然后写了一波
000 001 010 011
100 101 110 111
规律:发现只有第一位改变了,后面都没有变,然后推广到更大的数
AC后看了看评论区,嗯。。。果然在下还是不够机智orzzzzzzz
时间复杂度都是O(n),空间复杂度也都是O(n)
class Solution { //自己强行找规律
public:
vector<int> countBits(int num) {
vector<int> ans(num+1, 0);
ans[0] = 0;
ans[1] = 1;
ans[2] = 1;
ans[3] = 2;
int cnt = 0, cur = 4;
for (int i = 4; i <= num; i++) {
ans[i] = ans[cnt++] + 1;
if (cnt == cur) {
cnt = 0;
cur *= 2;
}
}
return ans;
}
};
i & (i - 1) 可得到小于i且二进制1比i少一位的数,然后在此基础上+1就好
class Solution { //评论区QAQ
public:
vector<int> countBits(int num) {
vector<int> ret(num+1, 0);
for (int i = 1; i <= num; ++i)
ret[i] = ret[i&(i-1)] + 1; //举一反三路漫漫兮啊,叹气
return ret;
}
};