Set the rightmost off bit
Last Updated :
05 Nov, 2021
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++
#include<iostream>
using namespace std;
int setRightmostUnsetBit( int n)
{
if ((n & (n + 1)) == 0)
return n;
return n | (n+1);
}
int main()
{
int n = 21;
cout << setRightmostUnsetBit(n);
return 0;
}
|
Java
public class GFG {
static int setRightmostUnsetBit( int n)
{
if ((n & (n + 1 )) == 0 )
return n;
return n | (n+ 1 );
}
public static void main(String[] args) {
int n = 21 ;
System.out.println(setRightmostUnsetBit(n));
}
}
|
Python 3
def setRightmostUnsetBit(n) :
if n & (n + 1 ) = = 0 :
return n
return n | (n + 1 )
if __name__ = = "__main__" :
n = 21
print (setRightmostUnsetBit(n))
|
C#
using System;
public class GFG {
static int setRightmostUnsetBit( int n)
{
if ((n & (n + 1)) == 0)
return n;
return n | (n+1);
}
public static void Main() {
int n = 21;
Console.WriteLine(setRightmostUnsetBit(n));
}
}
|
PHP
<?php
function setRightmostUnsetBit( $n )
{
if (( $n & ( $n + 1)) == 0)
return $n ;
return $n | ( $n + 1);
}
$n = 21;
echo setRightmostUnsetBit( $n );
?>
|
Javascript
<script>
function setRightmostUnsetBit(n)
{
if ((n & (n + 1)) == 0)
return n;
return n | (n + 1);
}
let n = 21;
document.write(setRightmostUnsetBit(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...