Search⌘ K

Switch Sign of a Number

Explore how to switch the sign of a number efficiently using the bitwise NOT operator and two's complement. This lesson helps you understand the underlying bit manipulation technique, apply the formula ~x + 1 to negate a number, and ensure constant time and space complexity in your solution.

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} ...