Java Toggle Bits Solution


  • 0
    F

    public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
    int i = 0;
    int j = 31;

        while(i < j) {
            if(getBitValue(n,i) ^ getBitValue(n,j)) {
                n = toggleBits(n,i,j);
            }
            i++;
            j--;
        }
        return n;
        
    }
    
    private boolean getBitValue(int n, int bitNum) {
        return (((n >> bitNum) & 1) == 1)? true : false;
    }
    
    private int toggleBits(int n , int i, int j) {
        n = n ^ (1 << i);
        n = n ^ (1 << j);
        return n;
    }
    

    }


Log in to reply
 

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