What is wrong in my logic


#1
        long res=0;
        for (int i=0;i<16;i++) {
            if ( (a&(1<<i)) != 0 && (a&(1<<(31-i))==0) ) {
                res=res|(1<<(31-i));
            }
            if ( (a&(1<<i)) == 0 && (a&(1<<(31-i)) != 0) ) {
                res=res|(1<<i);
            }
        }
        
        return res;

#2

It’s taking MSB as the sign bit idk why, compiler is shit. Also your condition is not checking both 1s case, your if conditions should look like this:

    if ((a&(1<<i)) != 0) {
                res=res|(1<<(31-i));
            }
    if ((a&(1<<(31-i))) != 0) {
                res= res|(1<<i);
            }

I ran the exact same thing on leetcode and it works, but here its taking 31st bit as sign bit so answer doesn’t match. This website can get frustrating sometimes!


#3

In both 1s case you don’t need to swap the bits so that’s why I haven’t made a special condition for both 1s.


#4

You’re not supposed to swap, you’ve to add it to the res at its complementory (ie 31-ith) index.
for eg: 11111111111111111111111111111101
your ouput will be: 2 (00000000000000000000000000000010)
It should be: 3221225471 (10111111111111111111111111111111)

Why because, if ith and (31-i) both are 1s, you are simply ignoring that case. you are supposed to add 1s in your result.


#5

yep, makes sense
I made the following changes to make it pass:
-added the if both bits (ith and 31-ith) are 1s case
-used 1L, so that 1 is unsigned long

public class Solution {
    public long reverse(long a) {
        long res=0;
        for (int i=0;i<16;i++) {
            if ( (a&(1L<<i)) != 0 && ((a&(1L<<(31-i)))==0) ) {
                res=res|(1L<<(31-i));
            }
            if ( (a&(1<<i)) == 0 && ((a&(1L<<(31-i))) != 0) ) {
                res=res|(1L<<i);
            }
            if ( (a&(1<<i)) != 0 && ((a&(1L<<(31-i))) != 0) ) {
                res=res|(1L<<(31-i));
                res=res|(1L<<i);
            }
        }
        
        return res;
    }
}