Yet another simple and clear Java solution


  • 0
    J

    Using a mask to filter the bits.

    public class Solution {
        public int findComplement(int num) {
            int mask = num;
            mask |= mask >> 1;
            mask |= mask >> 2;
            mask |= mask >> 4;
            mask |= mask >> 8;
            mask |= mask >> 16;
            return ~num & mask;
        }
    }
    

Log in to reply
 

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