Skip to main content

NOT Operator

Switch Sign of a Number

1 min read

We make use of bit manipulation to solve this problem. using a NOT operator.

In this coding question, we use the NOT operator to switch the sign of a number.

Problem Statement

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

Input: 10
 
Output: -10

Intuition

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

Formula

~x = (232 - 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
----------------------------

Solutions

Java

class SignChange {
    static int switchSign(int number){
      return ~number + 1;
    }

    public static void main( String args[] ) {
      int number = 8;
      System.out.println(switchSign(number));
    }
}

Python

def switchSign(number):
      return ~number + 1
    

number = 8
print(switchSign(number))

JavaScript

const switchSign = number => {
  return ~number + 1;
}

let number = 8;
console.log(switchSign(number));

C++

#include <iostream>

using namespace std;

int main() {
    int number = 8;
    cout << (~number + 1);
    return 0;
}

TypeScript

export const switchSign = (n: number): number => {
    return (~n + 1);
}

let n: number = 8;
console.log(switchSign(n));

Complexity Analysis

Time Complexity

We are not running a loop or scaling the inputs. The inputs never change. So the operation takes a single unit of time, which is O(1).

Space Complexity

We didn’t create an extra memory for this. So, the space complexity is O(1).

Reading Progress