[Leetcode] Reverse Bits

Source: Internet
Author: User

Reverse Bits

Reverse bits of a given the unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 ( Represented in binary as00111001011110000010100101000000).

Followup:
If This function is called many times, what would you optimize it?

Problem Solving Ideas:

Calculated by shifting. Here's the code:

Class Solution {public:    uint32_t reversebits (uint32_t N) {        uint32_t result=0;        int size = sizeof (uint32_t) *8;        for (int i=0; i<size; i++) {            result = result << 1;            result + = n%2;            n=n>>1;        }        return result;}    ;
Notice that if n is a very small number, there is no need to loop the size bit, if n is shifted to a position of 0, you can jump out of the loop. Result then left to move the remaining digits. The following is the optimized code:

Class Solution {public:    uint32_t reversebits (uint32_t N) {        uint32_t result=0;        int size = sizeof (uint32_t) *8;        int i=0;        Number of bits that have been moved        while (n!=0) {            result = result << 1;            result + = n%2;            n=n>>1;            i++;        }        Result <<= size-i;        return result;}    ;

[Leetcode] Reverse Bits

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.