Java: Simple to understand and Efficient


  • 0
    M

    '''
    public class Solution {
    public int findComplement(int num) {
    String s = Integer.toBinaryString(num);
    StringBuilder sb = new StringBuilder();

        for(int i = 0; i < s.length(); i++) {
            int a = s.charAt(i) ^ 1;
            sb.append((char) a);
        }
        
        return Integer.parseInt(sb.toString(), 2);
    }
    

    }
    '''


  • 0
    L

    public class Solution {
    public int findComplement(int num) {
    int mask = (Integer.highestOneBit(num) << 1) - 1;
    return num^mask;
    }
    }


Log in to reply
 

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