javabytesymmetricsymmetry

check if two bytes are symmetric


I heard this is a question asked in an interview, given two bytes, return true if they are symmetric

public boolean isSym(Byte firstByte, Byte secondByte);

01101000 and 00010110 are symmetric, but 01100000 and 11000000 are not. need to write the code in Java. Any ideas what is the best way to do so?


Solution

  • public boolean isSym(Byte firstByte, Byte secondByte)
    {
    
        for (int i = 0; i< 8 ; i++){
            if (bitAt(firstByte, i) != bitAt(secondByte, 7 - i))
                return false;
        }
    
        return true;
    }
    
    public byte bitAt(byte num, int position)
    {
       return (byte)((num >> position) & (byte)1);
    }