> ## Content Index
> Fetch the complete content index at: https://www.javahandbook.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Switch Sign of a Number
- URL: https://www.javahandbook.com/bitmask/switch-sign-of-a-number/
- Published: 2024-06-16T07:35:28.000Z
- Updated: 2024-06-17T03:41:48.000Z
- Author: Gopi Gorantala
- Tags: NOT Operator, #bitmask, #docs

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.

```json
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,

```json
>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.

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

### Solutions

### Java

```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

```py
def switchSign(number):
      return ~number + 1
    

number = 8
print(switchSign(number))

```

### JavaScript

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

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

### C++

```cpp
#include <iostream>

using namespace std;

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

### TypeScript

```ts
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)`.