leetcode 190. Reverse Bits 191. Number of 1 Bits

来源:互联网 发布:电脑画图软件 编辑:程序博客网 时间:2024/06/03 16:52

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?

class Solution {public:    uint32_t reverseBits(uint32_t n)     {        vector<int> num;        while ( n != 0 )         {            num.push_back(n%2);            n /= 2;        }                for(int i = num.size(); i < 32; i++)           num.push_back(0);                reverse(num.begin(), num.end());                uint32_t ret = 0;        for(int i = 0; i < num.size(); i++)        {               ret += num[i]<<i;        }        return ret;      }};



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.


class Solution {public:    int hammingWeight(uint32_t n)     {        int ret = 0;        for (int i = 0; i < 32; i++)            ret += ( ((n>>i) & 1) == 1) ? 1 : 0;        return ret;    }};




原创粉丝点击