Number Complement

Back to Homepage   |     Back to Code List


// Straightforward
class Solution {
    public int findComplement(int num) {
        String s = flip(decimal2binary(num));
        return binary2decimal(s);
    }
    
    String flip(String s) {
        StringBuilder sb = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (c == '1') {
                sb.append('0');
            } else {
                sb.append('1');
            }
        }
        
        return sb.toString();
    }
    
    private String decimal2binary(int num) {
        StringBuilder sb = new StringBuilder();
        while (num > 0) {
            sb.append(num % 2);
            num = num / 2;
        }
        
        return sb.toString();
    }
    
    private int binary2decimal(String bs) {
        int n = bs.length();
        int res = 0;
        for (int i = 0; i < n; i++) {
            if (bs.charAt(i) == '1') {
              res += (int) (Math.pow(2, i));
            }
        }
        
        return res;
    }
}

// Bit Manipulation
class Solution {
    public int findComplement(int num) {
        int n = num;
        int bit = 1;
        while (n != 0) {
            num = num ^ bit;
            bit = bit << 1;
            n = n >> 1;
        }
        
        return num;
    }
}