476. Number Complement #376
-
Topics: The complement of an integer is the integer you get when you flip all the
Given an integer Example 1:
Example 2:
Constraints:
Note: This question is the same as 1009. Complement of Base 10 Integer |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
We need to flip the bits of the binary representation of a given integer and return the resulting integer. Steps to solve the problem:
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';
}
// Step 3: Convert the flipped binary string back to an integer
return bindec($flipped);
}
// Example usage:
$num = 5;
echo findComplement($num); // Output: 2
$num = 1;
echo findComplement($num); // Output: 0
?> Explanation:
Example Runs:
This solution efficiently calculates the complement by flipping the bits of the binary representation of the given number. |
Beta Was this translation helpful? Give feedback.
We need to flip the bits of the binary representation of a given integer and return the resulting integer.
Steps to solve the problem:
0
to1
and1
to0
).Let's implement this solution in PHP: 476. Number Complement