📜  设置最右边的关闭位

📅  最后修改于: 2021-05-25 10:32:31             🧑  作者: Mango

编写一个程序,该程序设置整数的最右边的0位。
例子 :

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

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

如果对数字加1,则最右边未设置(或零位)之后的所有已设置位变为0,最右边未设置的位变为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


输出:
23