Skip to content

476. Number Complement #376

Answered by topugit
mah-shamim asked this question in Q&A
Aug 22, 2024 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

We need to flip the bits of the binary representation of a given integer and return the resulting integer.

Steps to solve the problem:

  1. Convert the number to its binary representation.
  2. Flip the bits (i.e., change 0 to 1 and 1 to 0).
  3. Convert the flipped binary string back to an integer.

Let's implement this solution in PHP: 476. Number Complement

<?php
function findComplement($num) {
    // Step 1: Get the binary representation of the number
    $binary = decbin($num);
    
    // Step 2: Flip the bits
    $flipped = '';
    for ($i = 0; $i < strlen($binary); $i++) {
        // If the bit is '1', change it to '0', otherwise change it to '1'
        $flipped .= $binary[$i] == '1' ? '0' : '1'

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@mah-shamim
Comment options

mah-shamim Aug 22, 2024
Maintainer Author

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants