Leetcode 190. Reverse Bits

Source: Internet
Author: User

Reverse Bits
    • Total Accepted: 71291
    • Total Submissions: 242226
    • Difficulty: Easy

Reverse bits of a given the unsigned integer.

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

followup: What would you optimize it when this function is called many times?

Idea: Binary number reversal.

Code:

Method One:

1 classSolution {2  Public:3 uint32_t reversebits (uint32_t N) {4n = (n >> -) | (N << -);5n = ((N &0xff00ff00) >>8) | (N &0x00ff00ff) <<8);6n = ((N &0xf0f0f0f0) >>4) | (N &0x0f0f0f0f) <<4);7n = ((N &0XCCCCCCCC) >>2) | (N &0x33333333) <<2);8n = ((N &0xaaaaaaaa) >>1) | (N &0x55555555) <<1);9         returnN;Ten     } One};


Method Two:

1 classSolution {2  Public:3 uint32_t reversebits (uint32_t N) {4         inti;5uint32_t res=0;6          for(i=0;i< +; i++){7res<<=1;8res|=n&1;9n>>=1;Ten         } One         returnRes; A     } -};

Leetcode 190. 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.