Simple C# Bit Shifting Solution


  • 1
    K
    • Do XOR between numberBASE2 and bit 1 (XOR produces complement of the bit)
      -Shift bit 1 left by one position each time
    public int FindComplement(int num) {
             string s = Convert.ToString(num, 2);
                for (int i = s.Length - 1; i >= 0; i--)
                    num = num ^ (1 << i);
                return num;
        }
    

  • 0
    S

    Based on your solution, modify it without for loop.
    public int FindComplement(int num) {
    String num2=Convert.ToString(num,2);
    int mask = (1<<num2.Length)-1;
    return ~num&mask;
    }

    The code could modify to one line too.
    public int FindComplement(int num) {
    return ~num&((1<<Convert.ToString(num,2).Length)-1);
    }


Log in to reply
 

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