Switch Sign of a Number

In this lesson, we make use of the NOT operator to switch the sign of a number.

Introduction

In this question, we take input and switch its sign.

Problem Statement

We need to write a program to switch the sign of a number.

Input: 10
 
Output: -10

Solution

We already know that 2’s complement of any number gives a negative number with the formula below.

Formula

~x = (2322^{32} - x)

For example,

 >if, x = 1
    ~x = -2

 if, y = 10
    ~y = -11

So if you see the pattern, the number is negated and converted to 2’s complement.

    number  = 8
   ~number  = -9
----------------------------
~number + 1 = (-9 + 1) = -8
----------------------------

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.