Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

Exercise: Bitwise NOT

Exercise 14 Very easy

Prerequisites for the exercise

  1. JavaScript 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 return back '' as well.

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

not('1010')
'0101'
not('1111')
'0000'
not('0000')
'1111'
not('00001')
'11110'
not('1')
'0'
not('')
''
View Solution

New file

Inside the directory you created for this course on JavaScript, create a new folder called Exercise-14-Bitwise-NOT and put the .html 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:

function not(inputStr) {
   var outputStr = '';

   for (var i = 0; i < inputStr.length; i++) {
      if (inputStr[i] === '1') {
         outputStr += '0';
      }
      else {
         outputStr += '1';
      }
   }
   return outputStr;
}

The variable outputStr is created to hold the NOT of the given binary string. At each iteration of the loop, the current character of the input binary string is inverted and then concatenated to outputStr to form the resulting string.

In the end, this very string is returned.