3 line pure C


  • 8
    O
    int findComplement(long num) {
        long i;
        for(i=1;i<=num;i*=2) num^=i; 
        return num;
    }
    

    I basically check every bit of number by XOR'ing it with appropriate power of 2 which leads to its invertion.
    For example:

    Entered: 4=>100;
    100 ^ 001 = 101;
    101 ^ 010 = 111;
    111 ^ 100 = 011;
    Out:     011=>3;
    

  • 0
    O

    Thank your idea let me know how to use XOR to solve this question
    slightly modify your code to return int type without implicit casting

    int findComplement(int num) {
    unsigned i=0;
    for(i=1;i<=num;i<<=1)
    num ^= i;

    return num;
    

    }


  • 0
    T

    brilliant solution


Log in to reply
 

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