Exercise: Bitwise NOT

Exercise 11 Very easy

Prerequisites for the exercise

  1. PHP Strings Basics
  2. All previous chapters

Objective

Create a function to perform the NOT binary operation on a binary string.

Description

Computers, as we all know, operate on binary numbers — numbers whose every single digit is either a 0 or a 1; hence the name 'binary'.

From the circuitry of the processor, to the input and output from I/O devices, to the wireless signals transmitted back and forth to the involved machinery, everything in the world of computers works on these magical numbers.

Typically, numerous operations are performed on binary numbers. Amongst the most common is the NOT operation, sometimes comprehensively referred to as the bitwise NOT, or the bitwise complement operation.

The operation proceeds as follows: each bit in the binary number is inverted. That is, if it is 0, it's made 1; and similarly if it's 1, it's made 0.

In this exercise, you ought to create a function not() that takes as input a binary number in the form of a string (such as '10100') and then returns back its value after performing the bitwise NOT operation on it, once again in the form of a string.

If an empty string ('') is given, the function should also return back an empty string ('').

Below shown are some examples of the usage of this function:

<?php

// not() defined here.

var_dump(not('1010'));
var_dump(not('1111'));
var_dump(not('00001'));
var_dump(not('1'));
var_dump(not(''));
string(4) "0101" string(4) "0000" string(5) "11110" string(1) "0" string(0) ""
View Solution

New file

Inside the directory you created for this course on PHP, create a new folder called Exercise-11-Bitwise-NOT and put the .php solution files for this exercise within it.

Solution

To solve this problem, we just need to iterate over the given string and determine the inversion of each character one-by-one. If it's '0', we use '1', otherwise we use '0'.

Here's the solution:

<?php

function not($str) {
   for ($i = 0; $i < strlen($str); $i++) {
      if ($str[$i] === '0') {
         $str[$i] = '1';
      }
      else {
         $str[$i] = '0';
      }
   }
   return $str;
}

Very easy, wasn't this?