设置最右边的未设置位

给定一个非负数n。问题是在n的二进制表示中设置最右边的未设置位 例如:

null
Input : 21Output : 23(21)10 = (10101)2Rightmost unset bit is at position 2(from right) as highlighted in the binary representation of 21.(23)10 = (10111)2The bit at position 2 has been set.Input : 2Output : 3

本文讨论了一种方法 文章 这篇文章讨论了另一种方法。 让输入数字为n。n+1将使所有位在最右边的未设置位(包括未设置位)之后翻转。所以,做n |(n+1)将得到所需的结果。

C++

#include <stdio.h>
// sets the rightmost unset bit
// of n and returns the result
int fun(unsigned int n)
{
return n | (n + 1);
}
// Driver Code
int main()
{
int n = 5;
printf ( "The number after setting the" );
printf ( " rightmost unset bit %d" , fun(n));
return 0;
}


JAVA

class GFG {
// sets the rightmost unset bit
// of n and returns the result
static int fun( int n)
{
return n | (n + 1 );
}
// Driver Code
public static void main(String[] args)
{
int n = 5 ;
System.out.printf( "The number "
+ "after setting the" );
System.out.printf( " rightmost "
+ " unset bit %d" , fun(n));
}
}
// This code is contributed by Smitha


Python3

# sets the rightmost unset bit
# of n and returns the result
def fun(n):
return n | (n + 1 )
# Driver Code
n = 5
print ( "The number after setting the" , end = "")
print ( " rightmost unset bit " , fun(n))
# This code is contributed by Smitha


C#

using System;
class GFG {
// sets the rightmost unset bit
// of n and returns the result
static int fun( int n)
{
return n | (n + 1);
}
// Driver Code
public static void Main()
{
int n = 5;
Console.Write( "The number "
+ "after setting the" );
Console.Write( " rightmost "
+ "unset bit " + fun(n));
}
}
// This code is contributed by Smitha


PHP

<?php
// PHP program to Set the rightmost
// unset bit
// sets the rightmost unset bit
// of n and returns the result
function fun( $n )
{
return $n | ( $n + 1);
}
// Driver Code
$n = 5;
echo "The number after setting the" ;
echo " rightmost unset bit " , fun( $n );
// This code is contributed m_kit
?>


Javascript

<script>
// sets the rightmost unset bit
// of n and returns the result
function fun(n)
{
return n | (n + 1);
}
// Driver Code
let n = 5;
document.write( "The number after setting the" );
document.write( " rightmost unset bit " , fun(n));
// This code is contributed by Manoj.
</script>


输出:

The number after setting the rightmost unset bit 7

时间复杂性: O(1)

辅助空间: O(1)

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享