OJ Practice 37--t190 Reverse Bits

Source: Internet
Author: User

Flips a 32-bit unsigned integer by bit,

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

Ideas

It is possible to switch between the end and end positions using bitwise operations and SHIFT operations.

But there is a tricky place where you want to turn the low to not use & (High shift), because if the high is 1, the low is 0, the result is 0, not equal to the high;

If you use | (High shift), there will be a high of 0, low is 1, the result is not equal to high. Therefore, bitwise operations cannot be used alone.

"My Code"

uint32_t reversebits (uint32_t N) {uint32_t temp1,temp2,low,high,dis; High=0x80000000; Low=0x1; Dis= to;  while(low<High ) {Temp1=high &N; Temp2=low &N; if(temp1!=Temp2) {            if(temp2&&!Temp1) {N+=High ; N-=Low ; }            Else if(!temp2&&Temp1) {N+=Low ; N-=High ; }} High>>=1; Low<<=1; Dis--; }        returnN; }

Reflection

For bit operation has been very unskilled, for bit exchange tangled for a long time. It doesn't seem like a smart thing to do.

Time consuming 9ms, ranked in the efficiency range of C.

"Other Code"

uint32_t reversebits (uint32_t N) {uint32_t answer;        uint32_t i; Answer=0; /*move a unsigned int number 1 to the left until it becomes full 0, and you get the length of the unsigned int within the machine .*/     for(i =1; I! =0; I <<=1) {Answer<<=1; if(N &1) {Answer |=1; } N>>=1; }        returnanswer; }

Evaluation

The law "new Space", but also just an unsigned integer size, insignificant, people code is very concise.

The beauty is in the For loop, the condition of the i!=0, I move left until the overflow is 0. This iterates over the required number of bits (which is not necessary here, known as 32).

Time consuming 10ms, ranking is the same as my algorithm.

So, there's always a better algorithm.

OJ Practice 37--t190 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.