# Bitwise Competitive Programming Hacks - GeeksforGeeks (2023)

`Precondition:It is recommended to referInteresting Facts about Bitwise Operators `

### To set a bit in the number "num":

If we want to start a littleNposition in the number "num" this can be done with the "OR" operator ( | ).

• First we shift the '1' to the left via (1<<n) to position n.
• Then use the "OR" operator to set the bit at that position. The OR operator is used because it sets the bit even if the bit was not previously set in the binary representation of the number num.

Observation:If the bit was already set, it would remain unchanged.

## C++

`#include<iostream>`

`to use` `namespace` `Standard;`

`// num is the number and pos is the position`

`// where we want to set the bit.`

`Empty` `Phrase(``int` `& num,``int` `pos)`

`{`

`// First step is shift '1', second`

`// step is bitwise OR`

`ob |= (1 << pos);`

`}`

`int` `mainly()`

`{`

`int` `num = 4, pos = 1;`

`set(num, pos);`

`cause << (``int``)(num) << endl;`

`to return` `0;`

`}`

## Java

`/*any package //don't write package names here */`

`matter` `java.io.*;`

`Classroom` `GFG {`

`public` `static` `Empty` `principal (String[] argumentos) {`

`int` `number =``4``, Pos =``1``;`

`num = set(num, pos);`

`System.out.println(num);`

`}`

`public` `static` `int` `Phrase(``int` `Number,``int` `pos){`

`// First step is shift '1', second`

`// step is bitwise OR`

`number |= (``1` `<< Pos);`

`to return` `Number;`

`}`

`}`

`// This code is contributed by geeky01adash.`

## Python3

`# num = number, pos = position where we want to set the bit`

`def` `Phrase` `(obs, pos):`

`# First step = Shift '1'`

`# Second pass = bitwise OR`

`number |``=` `(``1` `<<pos)`

`press``(Number)`

`ob, pos``=` `4``,``1`

`Phrase``(I can)`

`# This code is contributed by sarajadhav12052009`

## C #

`to use` `System;`

`public` `Classroom` `GFG{`

`static` `public` `Empty` `Mainly ()`

`{`

`int` `num = 4, pos = 1;`

`Phrase``(ob, pos);`

`}`

`// num = number, pos = position where we want to set the bit`

`static` `public` `Empty` `Phrase``(``int` `Number,``int` `pos)`

`{`

`// First step: Shift '1'`

`// Second step: bitwise OR`

`ob |= (1 << pos);`

`Console.WriteLine(num);`

`}`

`}`

`// This code is contributed by sarajadhav12052009`

## Javascript

`<script>`

`// num is the number and pos is the position`

`// where we want to set the bit.`

`function` `set(num,pos)`

`{`

`// First step is shift '1', second`

`// step is bitwise OR`

`ob |= (1 << pos);`

`console.log(parseInt(num));`

`}`

`sei num = 4;`

`last pos = 1;`

`set(num, pos);`

`// This code is contributed by akashish__`

`</script>`

Exit

`6`

Time complexity:O(1)
auxiliary room:O(1)

We pass the parameter via 'call by reference' to make permanent changes to the number.

### 2. To set/clear a bit at the nth position in number num:

Suppose we want to redefine something at the nth position at number "num", then we need to do it using "AND" (&) operator.

• First, we move the offset of "1" to position n via (1<<n) and then use the bitwise NOT operator "~" to reset this offset "1".
• After we delete that "1" shifted to the left, that is, H. set them to "0", we do "AND" (&) with the number "num" that resets the bit in the nth position.

## C++

`#include <iostream>`

`to use` `namespace` `Standard;`

`// The first step is to get a number that contains only 1 except for the specified position.`

`Empty` `not configured (``int` `&num,``int` `pos)`

`{`

`//Second step is bitwise and this number with the given number`

`ob &= (~(1 <<pos));`

`}`

`int` `mainly()`

`{`

`int` `number = 7;`

`int` `Pos = 1;`

`unset(ob, pos);`

`cout << num << endl;`

`to return` `0;`

`}`

## Java

`/*any package //don't write package names here */`

`matter` `java.io.*;`

`Classroom` `GFG {`

`public` `static` `Empty` `main(String[] argumentos)`

`{`

`int` `number =``7``, Pos =``1``;`

`num = unset(num, pos);`

`System.out.println(num);`

`}`

`public` `static` `int` `not configured (``int` `Number,``int` `pos)`

`{`

`// The second step is bitwise and this number with`

`// given number`

`number = number & (~(``1` `<< Pos));`

`to return` `Number;`

`}`

`}`

## Python3

`# First step: get all '1's except have`

`# position given`

`def` `undefined(num, pos):`

`# Second step: bitwise And this number with the given number`

`num &``=` `(~(``1` `<<pos))`

`press``(Number)`

`ob, pos``=` `7``,``1`

`disarm`

## C #

`to use` `System;`

`public` `Classroom` `GFG {`

`static` `public` `Empty` `Mainly()`

`{`

`// First step: Get a number consisting only of 1`

`// except for the given position`

`int` `num = 7, pos = 1;`

`unset(ob, pos);`

`}`

`static` `public` `Empty` `not configured (``int` `Number,``int` `pos)`

`{`

`// Second step: And bitwise this number with the`

`// given number`

`ob &= (~(1 <<pos));`

`Console.WriteLine(num);`

`}`

`}`

## Javascript

`// The first step is to get a number that contains only 1 except for the specified position.`

`function` `undefined(num,pos)`

`{`

`//Second step is bitwise and this number with the given number`

`ob &= ( ~ (1 << pos));`

`to return` `Number;`

`}`

`sei num = 7;`

`last pos = 1;`

`console.log (unset (num, pos));`

`// This code is contributed by akashish__`

Exit

`5`

Time complexity:O(1)
auxiliary room:O(1)

### 3. Toggle something in the nth position:

Toggle means turning bit on (1) if it was "off" (0) and "off" (0) if previously it was "on" (1). Let's use the 'XOR' operator here, which is this '^'. The reason for the "XOR" operator is in its properties.

• 'XOR' operator properties.
• 1^1 = 0
• 0^0 = 0
• 1^0 = 1
• 0^1 = 1
• If two bits are different, the "XOR" operator returns a set bit (1), otherwise it returns an unset bit (0).

## C++

`#include <iostream>`

`to use` `namespace` `Standard;`

`// First step is to change 1, second step is XOR with data`

`// number`

`Empty` `Trocar(``int``& num,``int` `pos) { num ^= (1 << pos); }`

`int` `mainly()`

`{`

`int` `number = 4;`

`int` `Pos = 1;`

`toggle(num, pos);`

`cout << num << endl;`

`to return` `0;`

`}`

## Java

`/*any package //don't write package names here */`

`matter` `java.io.*;`

`Classroom` `GFG {`

`public` `static` `Empty` `principal (String[] argumentos) {`

`int` `number =``4``, Pos =``1``;`

`num = toggle(num, pos);`

`System.out.println(num);`

`}`

`public` `static` `int` `Trocar(``int` `Number,``int` `pos){`

`// First step is offset 1, second step is XOR with given number`

`number ^= (``1` `<< Pos);`

`to return` `Number;`

`}`

`}`

`// This code is contributed by geeky01adash.`

## Python3

`def` `toggle(num, pos):`

`# First step: move '1'`

`# Second step: XOR num`

`number ^``=` `(``1` `<<pos)`

`press``(Number)`

`ob, pos``=` `4``,``1`

`toggle(num, pos)`

`# This code is contributed by sarajadhav12052009`

## C #

`to use` `System;`

`public` `Classroom` `GFG{`

`static` `public` `Empty` `Mainly ()`

`{`

`int` `num = 4, pos = 1;`

`toggle(num, pos);`

`}`

`static` `public` `Empty` `Trocar(``int` `Number,``int` `pos)`

`{`

`// First step: Shift '1'`

`// Second step: XOR num`

`ob ^= (1 << pos);`

`Console.WriteLine(num);`

`}`

`}`

`// This code is contributed by sarajadhav12052009`

## Javascript

`function` `toggle(num, pos) {`

`// First step is offset 1, second step is XOR with given number`

`ob ^= (1 << pos);`

`to return` `Number;`

`}`

`know num = 4,`

`Pos = 1;`

`num = toggle(num, pos);`

`console.log(num);`

`// This code is contributed by Prajwal Kandekar`

Exit

`6`

Time complexity:O(1)
auxiliary room:O(1)

### 4. Check whether the bit in the nth position is set or not:

This is easy to do with the "AND" operator.

• Left shift "1" to the specified position, then "AND" ("&").

## C++

`#include <iostream>`

`to use` `namespace` `Standard;`

`bool` `a position(``int` `Number,``int` `pos)`

`{`

`bool` `bit = num & (1 << pos);`

`to return` `Chunk;`

`}`

`int` `mainly()`

`{`

`int` `number = 5;`

`int` `Pos = 0;`

`bool` `bit = at_position (num, pos);`

`cout << bit << endl;`

`to return` `0;`

`}`

## Java

`/*any package //don't write package names here */`

`matter` `java.io.*;`

`Classroom` `GFG {`

`public` `static` `Empty` `main(String[] argumentos)`

`{`

`int` `number =``5``;`

`int` `Pos =``0``;`

`int` `bit = at_position (num, pos);`

`System.out.println (Bit);`

`}`

`public` `static` `int` `a position(``int` `Number,``int` `pos)`

`{`

`int` `bit = ob & (``1` `<< Pos);`

`to return` `Chunk;`

`}`

`}`

## Python3

`#-Code`

`def` `at_position(num,pos):`

`Chunk``=` `num & (``1``<<pos)`

`to return` `Chunk`

`Number``=` `5`

`pos``=` `0`

`Chunk``=` `at_position(num, pos)`

`press``(Chunk)`

## C #

`to use` `System;`

`Classroom` `GFG {`

`static` `Empty` `Mainly(``line``[ ] Arguments)`

`{`

`int` `number = 5;`

`int` `Pos = 0;`

`int` `bit = at_position (num, pos);`

`Console.WriteLine (Bit);`

`}`

`static` `int` `a position(``int` `Number,``int` `pos)`

`{`

`int` `bit = num & (1 << pos);`

`to return` `Chunk;`

`}`

`}`

## Javascript

`<script>`

`function` `at_position(num,pos)`

`{`

`to return` `ob & (1<<pos);`

`}`

`sei num = 5;`

`let pos = 0;`

`console.log (at_position (num, pos));`

`// contribution from akashish__`

`</script>`

Exit

`1`

Time complexity:O(1)
auxiliary room:O(1)

Note that we first shift "1" to the left and then use the "AND" operator to get a bit at that position. So if there is '1' in position 'pos' in 'num' then our variable 'bit' stores '1' after 'AND' otherwise if there is '0' in position 'pos' in number then 'num' will provide. than after 'AND' stores our variable '0' bit.

A few more quick hacks:

• Inverting each bit of a number/1's complement:If we want to invert each bit of a number, that is, change bit '0' to '1' and bit '1' to '0', we can do it with the help of the '~' operator. For example: if the number is num =00101100 (binary representation), then '~num' will be '11010011'.

This is also the "1's complement of the number".

## C++

`#include <iostream>`

`to use` `namespace` `Standard;`

`int` `mainly()`

`{`

`int` `number = 4;`

`// reverse each bit of number num`

`cout << (~num);`

`to return` `0;`

`}`

## Java

`/*any package //don't write package names here */`

`matter` `java.io.*;`

`Classroom` `GFG {`

`public` `static` `Empty` `principal (String[] argumentos) {`

`int` `number =``4``;`

`// reverse each bit of number num`

`number = (~number);`

`System.out.println(num);`

`}`

`}`

## Python3

`Number``=` `4`

`# Invert each bit of number num`

`press``(~number)`

## C #

`to use` `System;`

`public` `Classroom` `GFG{`

`static` `public` `Empty` `Mainly ()`

`{`

`int` `number = 4;`

`// reverse each bit of number num`

`Console.WriteLine(~num);`

`}`

`}`

## Javascript

`<script>`

`sei num = 4;`

`// reverse each bit of number num`

`console.log(~num);`

`</script>`

Exit

`-5`

Time complexity:O(1)
auxiliary room:O(1)

• Two's complement of the number:The two's complement of a number is one's complement + 1.

So formally we can have the 2's complement by finding the 1's complement and adding 1 to the result i.e. (~num+1) or what else we can do is use the '-' operator.

## C++

`#include <iostream>`

`to use` `namespace` `Standard;`

`int` `mainly()`

`{`

`int` `number = 4;`

`int` `twos_complement = -num;`

`cause <<``"This is two's complement"` `<< two's complement << endl;`

`cause <<``"This is also two's complement"` `<< (~num+1) << endl;`

`to return` `0;`

`}`

## Java

`/*any package //don't write package names here */`

`matter` `java.io.*;`

`Classroom` `GFG {`

`public` `static` `Empty` `main(String[] argumentos)`

`{`

`int` `number =``4``;`

`int` `twos_complement = -num;`

`System.out.println(``"This is two's complement"`

`+ two's complement);`

`System.out.println(``"This is also two's complement"`

`+ (~number +``1``));`

`}`

`}`

`// This code is contributed by geeky01adash.`

## Python3

`Number``=` `4`

`two's complement``=` `-``Number`

`press``(F``"This is two's complement {twos_complement}"``)`

`press``(F``"This is also two's complement {~num + 1}"``)`

`# This code is contributed by sarajadhav12052009`

## C #

`to use` `System;`

`public` `Classroom` `GFG{`

`static` `public` `Empty` `Mainly ()`

`{`

`int` `number = 4;`

`int` `twos_complement = -num;`

`Console.WriteLine(``"This is two's complement"` `+ two's complement);`

`Console.WriteLine(``"This is also two's complement"` `+ (~num+1));`

`}`

`}`

`// This code is contributed by sarajadhav12052009`

## Javascript

`<script>`

`sei num = 4;`

`let twos_complement = -num;`

`Console.log (``"This is two's complement"` `+ two's complement);`

`Console.log (``"This is also two's complement"` `+ (~num+1));`

`// This code is contributed by akashish__`

`</script>`

Exit

`This is two's complement -4. This is also two's complement -4`

Time complexity:O(1)
auxiliary room:O(1)

### Removing the lowest bitset:

In many situations we want to remove the lowest bit set, for example in a binary indexed tree data structure counting the number of bits set in a number. We do something like this:

`X = X & (X-1)`

But how does it work? Let's see this with an example, let X = 1100.

• (X-1) inverts all bits until it finds the smallest quantity "1", and also inverts this smallest quantity "1".
• X-1 becomes 1011. After "WALKING" X with X-1, we remove the lowest set bit.

## C++

`#include <iostream>`

`to use` `namespace` `Standard;`

`Empty` `strip_last_set_bit(``int` `&num)`

`{`

`num = num & (num-1);`

`}`

`int` `mainly()`

`{`

`int` `number = 7;`

`strip_last_set_bit(num);`

`cout << num << endl;`

`to return` `0;`

`}`

## Java

`matter` `java.io.*;`

`Classroom` `GFG {`

`public` `static` `Empty` `main(String[] argumentos)`

`{`

`int` `number =``7``;`

`num = strip_last_set_bit(num);`

`System.out.println(num);`

`}`

`public` `static` `int` `strip_last_set_bit(``int` `Number)`

`{`

`to return` `I know -``1``);`

`}`

`}`

## Python3

`def` `strip_last_set_bit(num):`

`num &``=` `(Anz``-` `1``)`

`press``(Number)`

`Number``=` `7`

`strip_last_set_bit(num)`

## C #

`to use` `System;`

`public` `Classroom` `GFG{`

`static` `public` `Empty` `Mainly ()`

`{`

`int` `number = 7;`

`strip_last_set_bit(num);`

`}`

`static` `public` `Empty` `strip_last_set_bit(``int` `Number)`

`{`

`number &= (number - 1);`

`Console.WriteLine(num);`

`}`

`}`

## Javascript

`<script>`

`function` `strip_last_set_bit(num)`

`{`

`to return` `number & (number-1);`

`}`

`sei num = 7;`

`console.log(strip_last_set_bit(num));`

`</script>`

Exit

`6`

Time complexity:O(1)
auxiliary room:O(1)

### Get the lowest register bit of a number:

This is achieved using the expression 'X &(-X)'. Let's see this with an example: Let X = 00101100. Then ~X(1's complement) will be '11010011' and 2's complement will be (~X+ 1 or -X), ie '11010100'. So if 'E' the original number 'X' with its two's complement, which is '-X', we get the lowest bit set.

`00101100& 11010100----------- 00000100`

## C++

`#include <iostream>`

`to use` `namespace` `Standard;`

`int` `menor_bit_set(``int` `Number)`

`{`

`int` `ret = num & (-num);`

`to return` `turn back;`

`}`

`int` `mainly()`

`{`

`int` `number = 10;`

`int` `ans = less_set_bit(num);`

`cout << ans << endl;`

`to return` `0;`

`}`

## Java

`matter` `java.io.*;`

`Classroom` `GFG {`

`public` `static` `Empty` `main(String[] argumentos)`

`{`

`int` `number =``10``;`

`int` `ans = less_set_bit(num);`

`System.out.println(ans);`

`}`

`public` `static` `int` `menor_bit_set(``int` `Number)`

`{`

`int` `ret = num & (-num);`

`to return` `turn back;`

`}`

`}`

## Python3

`def` `minor_set_bit(num):`

`num &``=` `(``-``Number)`

`press``(Number)`

`Number``=` `10`

`minor_bit_set(num)`

## Javascript

`// Function to set the lowest bit`

`function` `minor_bit_set(num)`

`{`

`// Take e from num and -ve from num`

`let ret = num & (-num);`

`to return` `turn back;`

`}`

`// driver code`

`I know num = 10`

`let ans = smallest_set_bit(num)`

`console.log(ans)`

## C #

`to use` `System;`

`public` `Classroom` `GFG {`

`static` `public` `Empty` `Mainly()`

`{`

`int` `number = 10;`

`bit_set_minor(num);`

`}`

`static` `public` `Empty` `menor_bit_set(``int` `Number)`

`{`

`number &= (~number + 1);`

`Console.WriteLine(num);`

`}`

`}`

Exit

`2`

Divide by 2 and multiply by 2 are also very common in loops in competitive programming, so using bitwise operators can help speed up code.

Divide by 2 using the right shift operator:

`00001100 >> 1 (00001100 is 12)------------00000110 (00000110 is 6)`

## C++

`#include <iostream>`

`to use` `namespace` `Standard;`

`int` `mainly()`

`{`

`int` `number = 12;`

`int` `ans = num>>1;`

`cout << ans << endl;`

`to return` `0;`

`}`

## Java

`matter` `java.io.*;`

`Classroom` `GFG {`

`public` `static` `Empty` `main(String[] argumentos)`

`{`

`int` `number =``12``;`

`int` `years = ob >>``1``;`

`System.out.println(ans);`

`}`

`}`

## Python3

`Number``=` `12`

`press``(Number >>``1``)`

## C #

`to use` `System;`

`public` `Classroom` `GFG{`

`static` `public` `Empty` `Mainly ()`

`{`

`int` `number = 12;`

`Console.WriteLine(num >> 1);`

`}`

`}`

## Javascript

`<script>`

`Guerra` `number = 12;`

`Guerra` `ans = num>>1;`

`console.log(ans);`

`</script>`

Exit

`6`

Time complexity:O(1)
auxiliary room:O(1)

Multiply by 2 using the left shift operator:

`00001100 << 1 (00001100 is 12)------------00011000 (00000110 is 24)`

## C++

`#include <iostream>`

`to use` `namespace` `Standard;`

`int` `mainly()`

`{`

`int` `number = 12;`

`int` `ans = num<<1;`

`cout << ans << endl;`

`to return` `0;`

`}`

## Java

`/*any package //don't write package names here */`

`matter` `java.io.*;`

`Classroom` `GFG {`

`public` `static` `Empty` `principal (String[] argumentos) {`

`int` `number =``12``;`

`int` `ans = num<<``1``;`

`System.out.println(ans);`

`}`

`}`

`// This code is contributed by geeky01adash.`

## C #

`to use` `System;`

`public` `Classroom` `GFG{`

`static` `public` `Empty` `Mainly ()`

`{`

`int` `number = 12;`

`Console.WriteLine(num << 1);`

`}`

`}`

`// This code is contributed by sarajadhav12052009`

## Python3

`# Python program for the above approach`

`Number``=` `12`

`response``=` `number <<``1`

`press``(response)`

`# This code is contributed by Shubham Singh`

## Javascript

`<script>`

`// Javascript program for the above approach`

`Guerra` `number = 12;`

`Guerra` `ans = num<<1;`

`document.write(ans);`

`//This code is contributed by Shubham Singh`

`</script>`

Exit

`24`

Time complexity:O(1)
auxiliary room:O(1)

Bit tricks for competitive programming
ReferBitWise Operator Articlesfor more articles on bit hacks.

This article was contributed byPankaj Mishra. If you like GeeksforGeeks and want to contribute, you can also write an article and send your article to review-team@geeksforgeeks.org. See your article appear on the main page of GeeksforGeeks and help other geeks.

my personal notesarrow_drop_up

Top Articles
Latest Posts
Article information

Author: Nathanael Baumbach

Last Updated: 31/12/2023

Views: 5991

Rating: 4.4 / 5 (55 voted)

Author information

Name: Nathanael Baumbach

Birthday: 1998-12-02

Address: Apt. 829 751 Glover View, West Orlando, IN 22436

Phone: +901025288581

Job: Internal IT Coordinator

Hobby: Gunsmithing, Motor sports, Flying, Skiing, Hooping, Lego building, Ice skating

Introduction: My name is Nathanael Baumbach, I am a fantastic, nice, victorious, brave, healthy, cute, glorious person who loves writing and wants to share my knowledge and understanding with you.