Ask Question
8 June, 09:02

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Note: The given integer is guaranteed to fit within the range of a 32-bit signed integer. You could assume no leading zero bit in the integer's binary representation.

+3
Answers (1)
  1. 8 June, 09:49
    0
    var findComplement = function (num) {

    var start = false;

    for (var i = 31; i > = 0; - -i) {

    if (num & (1 << i)) {//find the leftmost hightest bit 1 and start from there

    start = true;

    }

    if (start) {

    num ^ = (1 << i);

    }

    }

    return num;

    };

    var findComplement = function (num) {

    var bits = num. toString (2);

    var complement = '';

    for (var i=0; i
    {

    complement + = (bits[i]==1?0:1);

    }

    return parseInt (complement, 2);

    };

    Explanation:

    The jа vascript code above would accept a number in the variable complemnt and using the parseint keyword, it converts it to a binary value of that number.

    Each bit is converted from the least to the most significant bit, then it is returned to the find compliment function and converted back to an integer.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Note: The ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers