算法设计:关闭最右边的设置位

2021年3月15日09:08:51 发表评论 819 次浏览

本文概述

编写一个程序, 以使整数的最右边的设置位无效。

例子 :

Input:  12 (00...01100)
Output: 8 (00...01000)

Input:  7 (00...00111)
Output: 6 (00...00110)

推荐:请尝试以下方法{IDE}首先, 在继续解决方案之前。

令输入数字为n。 n-1将使所有位在最右边的设置位(包括设置位)之后翻转。因此, 执行n&(n-1)将给我们所需的结果。

C ++

#include <bits/stdc++.h>
using namespace std;
  
// unsets the rightmost set bit 
// of n and returns the result 
int fun(unsigned int n) 
{ 
     return n & (n - 1); 
} 
  
// Driver Code 
int main() 
{ 
     int n = 7; 
     cout<< "The number after unsetting the" ; 
     cout<< " rightmost set bit " <<fun(n); 
     return 0; 
} 
  
  
  
//This code is contributed by rathbhupendra

C

#include <stdio.h>
  
// unsets the rightmost set bit
// of n and returns the result
int fun(unsigned int n)
{
     return n & (n - 1);
}
  
// Driver Code
int main()
{
     int n = 7;
     printf ( "The number after unsetting the" );
     printf ( " rightmost set bit %d" , fun(n));
     return 0;
}

Java

// Java program to unset the
// rightmost set bit of an integer.
  
class GFG {
  
     /* unsets the rightmost set bit
      of n and returns the result */
     static int fun( int n)
     {
         return n & (n - 1 );
     }
  
     // Driver code
     public static void main(String arg[])
     {
         int n = 7 ;
         System.out.print( "The number after unsetting "
                          + "the rightmost set bit " + fun(n));
     }
}
  
// This code is contributed by Anant Agarwal.

Python3

# unsets the rightmost set bit
# of n and returns the result 
def fun(n):
  
      return n & (n - 1 )
  
# Driver code
  
n = 7
print ( "The number after unsetting the rightmost set bit" , fun(n))
  
# This code is contributed
# by Anant Agarwal.

C#

// C# program to unset the
// rightmost set bit of an integer.
using System;
  
class GFG {
  
     /* unsets the rightmost set bit
     of n and returns the result */
     static int fun( int n)
     {
         return n & (n - 1);
     }
  
     // Driver code
     public static void Main()
     {
         int n = 7;
         Console.Write( "The number after unsetting "
                       + "the rightmost set bit " + fun(n));
     }
}
  
// This code is contributed by Sam007

的PHP

<?php
// unsets the rightmost set bit 
// of n and returns the result 
function fun( $n )
{
return $n & ( $n - 1);
} 
  
// Driver Code
$n = 7;
echo "The number after unsetting the" .
      " rightmost set bit " , fun( $n );
  
// This code is contributed by vt_m.
  
?>

输出:

The number after unsetting the rightmost set bit 6

如果你发现上述代码/算法有误, 请写评论, 或者找到解决同一问题的更好方法

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: