Invert bits of binary representation of number
int n = 0; This initialization is not used.  It could simply be int n;, or could be int n = !(num &amp; 1); inside the loop, to restrict the scope of n.



This loop:

int k = 0;
while (num) {
    ...
    k++;
}


could be written as:

for(int k = 0; num; k++) {
    ...
}




Since you are doing bit manipulation, instead of using addition, you should probably use a “binary or” operation to merge the bit into your accumulator:

    b = b | (n &lt;&lt; k);


or simply:

    b |= n &lt;&lt; k;




Bug

You are not inverting the most significant zero bits.  Assuming an 8-bit word size, the binary compliment of 9 (0b00001001) should be 0b11110110, not 0b00000110.   And the compliment of that should return to the original number (0b00001001), but instead yields 0b00000001.



And, as mentioned by @Martin R, you could simply return ~num;