Bit opereation by Java optimized for calling many times.


  • 3
    X

    We stored 0x00000001~0x11111111 in advance.

    public class Solution {

    private static int bitmap[]=new int[32];
    static
    {
        for(int i=0;i<32;i++)
        {
            bitmap[i]=(1<<i);
        }
    }
    
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        
        int r=0;
        for(int i=0;i<32;i++)
        {
            if((n&bitmap[i])!=0)
                r|=bitmap[31-i];
        }
        return r;
    }
    

    }


  • 0
    T

    Will array lookup really faster than shift operation?

    Shift operation is very cheap, but what about array lookup?


  • 0
    X

    I think it's hard to say. Maybe they are just similar.
    I was thought java is running based on stack.
    So In this way, it may help for doing some optimization.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.