Just another WordPress.com site

Solution Of ACM UVA 594

You need to swap bits!

The input is an integer N, convert this to 32-bit integer. You have to swap 8 bits of Least Significant Bit to Most Significant Bit. Partition them into this:

X1 X2 X3 X4

Where X1,2,3, & 4 is 8-bit from the complete 32-bit integer.
Then you need to swap it so the position is like this:

X4 X3 X2 X1

So, use bitwise manipulation

<< Shift Left
>> Shift Right
& bitwise And

Another Procedure :

       If you are familiar with union then you can solve this very easily . Take a glance at the following code .

Code :

#include<iostream>
#include<cstdio>
using namespace std;

union
{
int Num;
char ch[4];
} A,B;

int main()
{
long int N;
while( scanf(“%d”,&A.Num)==1 )
{
B.ch[0]=A.ch[3];
B.ch[1]=A.ch[2];
B.ch[2]=A.ch[1];
B.ch[3]=A.ch[0];

printf(“%d converts to %d\n”,A.Num,B.Num);
}
return 0;
}

Explanation

One solution is to extract each byte of the solution using masks, shift each byte appropriately, and finally using a bitwise OR to merge the bytes back to one. Essentially just reverse the bytes of a 32-bit signed integer.

11111111 00000000 10101010 01010101

becomes

01010101 10101010 00000000 11111111

Input

0
123456789
-123456789
1
16777216
20034556
-1
-2
-65536

 Output

0 converts to 0
123456789 converts to 365779719
-123456789 converts to -349002504
1 converts to 16777216
16777216 converts to 1
20034556 converts to -55365375
-1 converts to -1
-2 converts to -16777217
-65536 converts to 65535

Comments on: "Solution Of ACM UVA 594" (3)

  1. #include
    using namespace std;
    #define SWAP(a,b) a= a^b, b=a^b, a=a^b
    int main() {
    int o, reverse;
    while (scanf(“%d”, &o) == 1) {
    reverse = o;
    char * bits = (char*) &reverse;
    SWAP(bits[0], bits[3]), SWAP(bits[1], bits[2]);
    printf(“%d converts to %d\n”, o, reverse);
    }
    return 0;
    }

  2. prasanth25k said:

    gud explanation🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: