# Set the rightmost off bit

Write a program that sets the rightmost 0 bit of an integer.
Examples :

```Input:  12 (00...01100)
Output: 13 (00...01101)

Input:  7 (00...00111)
Output: 15 (00...01111)```

If we add 1 to a number, all set bits after rightmost unset (or zero bit) become 0 and the rightmost unset bit becomes 1.

## C++

 `// CPP program to set the rightmost unset bit` `#include` `using` `namespace` `std; ` `  `  `int` `setRightmostUnsetBit(``int` `n) ` `{     ` `    ``// If all bits are set  ` `    ``if` `((n & (n + 1)) == 0)     ` `        ``return` `n; ` `      `  `    ``// Set rightmost 0 bit` `    ``return` `n | (n+1);     ` `} ` `  `  `// Driver program to test above ` `int` `main() ` `{ ` `    ``int` `n = 21; ` `    ``cout << setRightmostUnsetBit(n); ` `    ``return` `0; ` `}`

## Java

 `//Java  program to set the rightmost unset bit`   `public` `class` `GFG {`   `    ``static` `int` `setRightmostUnsetBit(``int` `n) ` `    ``{     ` `     ``// If all bits are set  ` `     ``if` `((n & (n + ``1``)) == ``0``)     ` `         ``return` `n; ` `        `  `     ``// Set rightmost 0 bit` `     ``return` `n | (n+``1``);     ` `    ``} `   `    ``//Driver program to test above ` `    ``public` `static` `void` `main(String[] args) {`   `         ``int` `n = ``21``; ` `         ``System.out.println(setRightmostUnsetBit(n)); ` `    ``}`   `}`

## Python 3

 `# Python3 program to set the ` `# rightmost unset bit `   `def` `setRightmostUnsetBit(n) :`   `    ``# If all bits are set ` `    ``if` `n & (n ``+` `1``) ``=``=` `0` `:` `        ``return` `n` `    `  `    ``# Set rightmost 0 bit ` `    ``return` `n | (n``+``1``)`   `# Driver code     ` `if` `__name__ ``=``=` `"__main__"` `:`   `    ``n ``=` `21` `    ``print``(setRightmostUnsetBit(n))`   `# This code is contributed` `# by ANKITRAI1`

## C#

 `// C# program to set the rightmost unset bit`   `using` `System;`   `public` `class` `GFG {` ` `  `    ``static` `int` `setRightmostUnsetBit(``int` `n) ` `    ``{     ` `     ``// If all bits are set  ` `     ``if` `((n & (n + 1)) == 0)     ` `         ``return` `n; ` `         `  `     ``// Set rightmost 0 bit` `     ``return` `n | (n+1);     ` `    ``} ` ` `  `    ``//Driver program to test above ` `    ``public` `static` `void` `Main() {` ` `  `         ``int` `n = 21; ` `         ``Console.WriteLine(setRightmostUnsetBit(n)); ` `    ``}` ` `  `}`

## PHP

 ``

## Javascript

 ``

Output:

`23`

Time Complexity: O(1)

Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next