Leetcode-reverse Bits

Source: Internet
Author: User

Reverse bits of a given the unsigned integer.

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

Title: To an unsigned 32-bit integer, reverse the binary representation (for example, 6, binary is 110, upside is 011, the corresponding 10-decimal integer is 3). Returns the decimal integer after the reversal.

The procedure is simple, for a given number, starting from the lowest bit, separating it, the lowest bit is the highest bit of the answer. Loop 32 times, dividing the number of inputs by 2 each time, and multiplying the answer by 2.

The problem is that the program runs as fast as possible, and I do 2 solutions, one using a bitwise operation to separate the last number, and one to separate by taking the remainder. As a result, I was surprised that the computation of the remainder was faster than the bitwise operation.

classSolution { Public: uint32_t reversebits (uint32_t N) {uint32_t ans=0; intbit =0; inti =0;  while(I++ < +) {bit= n%2;//determine whether the last number is 0 or 1 by taking the remainderAns = ((ans <<1) +bit); N= N >>1; }    returnans; }};classSolution { Public: uint32_t reversebits (uint32_t N) {uint32_t ans=0;  for(inti =0; I < +; i++) {ans<<=1; Ans|= (N &1);////The last 1 bits are obtained by bitwise operation, plus the original numberN >>=1; }    returnans;};

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.