476.Number Complement

1

https://leetcode.com/problems/number-complement/discuss/95992

class Solution {
    public int findComplement(int num) {
        int mask = 1;
        while(mask < num){
            mask = (mask << 1) | 1;
        }
        mask >>= 1;
        return ~num  & mask;
    }
}

Or

public class Solution {
    public int findComplement(int num) {
        return ~num & ((Integer.highestOneBit(num) << 1) - 1);
    }
}


Or

class Solution {
    public int findComplement(int num) {
        int n = 0;
        while(n < num){
            n = (n << 1) | 1;
        }
        return n - num;
    }
}

results matching ""

    No results matching ""