[Leetcode] Reverse Bits

Source: Internet
Author: User

1Reverse bits of a given, unsigned integer.

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

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

Solving Ideas 1

The procedure is similar to converting a string to shaping, except that it is binary and is processed from the right.

Implementation Code 1
//runtime:10 Ms#include <iostream>#include "inttypes.h"using namespace STD;classSolution { Public: uint32_t reversebits (uint32_t N) {uint32_t result =0;inti = +; while(i--) {result = result *2+ (N &0x1); N >>=1; }returnResult }};intMain () {solution S;cout<<s.reversebits (43261596) <<endl;return 0;}
Solving Ideas 2

uint32_t the length of the machine on the basis of idea 1

Implementation Code 2
//runtime:9 ms  # Include <iostream>   #include "Inttypes.h"  using  namespace  STD ; class  Solution {public : uint32_t reversebits (uint32_t N) {uint32_t result = 0 ; uint32_t i; for  (i = 1 ; I! = 0 ; I <<= 1 ) {result <<= 1 ; Result |= (N & 0x1 ); n >>= 1 ; } return  result; }};
Solving Ideas 3

Solve problems by exchanging bits of unsigned integer numbers directly

Implementation Code 3
//runtime:10 MsclassSolution { Public: uint32_t reversebits (uint32_t N) {uint32_t i; uint32_t x =sizeof(x) *8;//uint32_t number of digits         for(i =0; I < x/2; i++) {swapbit (n, I, X-i-1); }returnN }voidSwapbit (uint32_t& N, uint32_t I, uint32_t j) {uint32_t lo = (n >> i) &0x1; uint32_t hi = (n >> j) &0x1;if(lo ^ hi)//I and J-bits are not equal{//0 ^ 1 = 1            //1 ^ 1 = 0 for Exchange purposesN ^= ((1U<< i) | (1U<< j)); }    }};

[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.