📜  将给定N加1后更改的位数计数

📅  最后修改于: 2021-05-25 03:09:36             🧑  作者: Mango

给定一个整数N  。任务是查找在给定数字加1后更改的位数。
例子

Input : N = 5
Output : 2
After adding 1 to 5 it becomes 6.
Binary representation of 5 is 101.
Binary representation of 6 is 110.
So, no. of bits changed is 2.

Input : N = 1
Output : 2

有三种方法可以找到将给定值N加1后获得的结果中的更改位数:

  • 方法1:将1与给定的整数相加,比较N的位数和相加后得到的结果,并对不匹配位数进行计数。
  • 方法2:如果将1加到N,则更改的总位数由从右起第1个零的位置(即LSB为零)定义。在这种情况下,将1加1,然后对其进行更改,并将进位1传递到其下一位;但是,如果将1加到0,则只有0变为1,并且不再传递进位。
  • 方法3:为了在将1加到给定数字时查找变化的位数,请对n和n + 1进行XOR,然后计算所得XOR值中的置位位数。

以下是方法3的实现:

C++
// CPP program to find the number
// of changed bit
#include 
using namespace std;
 
// Function to find number of changed bit
int findChangedBit(int n)
{
    // Calculate xor of n and n+1
    int XOR = n ^ (n + 1);
 
    // Count set bits in xor value
    int result = __builtin_popcount(XOR);
 
    // Return the result
    return result;
}
 
// Driver function
int main()
{
    int n = 6;
    cout << findChangedBit(n) << endl;
 
    n = 7;
    cout << findChangedBit(n);
 
    return 0;
}


Java
// Java program to find the number
// of changed bit
class GFG
{
 
// Function to find number of changed bit
static int findChangedBit(int n)
{
    // Calculate xor of n and n+1
    int XOR = n ^ (n + 1);
 
    // Count set bits in xor value
    int result = Integer.bitCount(XOR);
 
    // Return the result
    return result;
}
 
// Driver code
public static void main(String[] args)
{
    int n = 6;
    System.out.println(findChangedBit(n));
 
    n = 7;
    System.out.println(findChangedBit(n));
}
}
 
// This code contributed by Rajput-Ji


Python3
# Python 3 program to find the number
# of changed bit
 
# Function to find number of changed bit
def findChangedBit(n):
     
    # Calculate xor of n and n+1
    XOR = n ^ (n + 1)
 
    # Count set bits in xor value
    result = bin(XOR).count("1")
 
    # Return the result
    return result
 
# Driver Code
if __name__ == '__main__':
    n = 6
    print(findChangedBit(n))
 
    n = 7
    print(findChangedBit(n))
 
# This code is contributed by
# Surendra_Gangwar


C#
// C# program to find the number
// of changed bit
using System;
     
class GFG
{
 
// Function to find number of changed bit
static int findChangedBit(int n)
{
    // Calculate xor of n and n+1
    int XOR = n ^ (n + 1);
 
    // Count set bits in xor value
    int result = bitCount(XOR);
 
    // Return the result
    return result;
}
static int bitCount(int x)
{
 
    // To store the count
    // of set bits
    int setBits = 0;
    while (x != 0)
    {
        x = x & (x - 1);
        setBits++;
    }
 
    return setBits;
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 6;
    Console.WriteLine(findChangedBit(n));
 
    n = 7;
    Console.WriteLine(findChangedBit(n));
}
}
 
/* This code contributed by PrinciRaj1992 */


Javascript


输出:
1
4