📌  相关文章
📜  给定整数中匹配设置和未设置位的计数。

📅  最后修改于: 2022-05-13 01:56:06.122000             🧑  作者: Mango

给定整数中匹配设置和未设置位的计数。

两个整数XY的任务是通过不考虑二进制形式中较大数字的最左边设置位之后的任何前导零来找到在其二进制表示中相同的位数。

例子:

方法:

直觉:

算法:

  • 继续执行以下步骤,直到XY不是0
    • 通过X % 2Y % 2计算给定整数XYLSB ,并检查两者是否相同。
      • 如果相同,则增加答案
    • 将两个给定的整数右移1

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to find the number of same bit between
// two integer.
int solve(int X, int Y)
{
    int ans = 0;
 
    while (X != 0 || Y != 0) {
        // Check if both LSB are same or not
        if (X % 2 == Y % 2)
            ans++;
 
        // Right shift the both given integer by 1
        X >>= 1;
        Y >>= 1;
    }
 
    return ans;
}
 
// Driver code
int main()
{
    int X = 10, Y = 6;
 
    // Find number of same bits
    cout << solve(X, Y);
 
    return 0;
}


Java
// Java implementation of the approach
import java.io.*;
 
class GFG
{
 
  // Function to find the number of same bit between
  // two integer.
  public static int solve(int X, int Y)
  {
    int ans = 0;
 
    while (X != 0 || Y != 0)
    {
       
      // Check if both LSB are same or not
      if (X % 2 == Y % 2)
        ans++;
 
      // Right shift the both given integer by 1
      X >>= 1;
      Y >>= 1;
    }
 
    return ans;
  }
 
  public static void main(String[] args)
  {
    int X = 10, Y = 6;
 
    // Find number of same bits
    System.out.print(solve(X, Y));
  }
}
 
// This code is contributed by Rohit Pradhan


C#
// C# implementation of the approach
using System;
 
public class GFG{
 
  // Function to find the number of same bit between
  // two integer.
  public static int solve(int X, int Y)
  {
    int ans = 0;
 
    while (X != 0 || Y != 0)
    {
 
      // Check if both LSB are same or not
      if (X % 2 == Y % 2)
        ans++;
 
      // Right shift the both given integer by 1
      X >>= 1;
      Y >>= 1;
    }
 
    return ans;
  }
 
  static public void Main (){
    int X = 10, Y = 6;
 
    // Find number of same bits
    Console.Write(solve(X, Y));
  }
}
 
// This code is contributed by hrithikgarg03188.


输出
2

时间复杂度:O(1)
辅助空间: O(1)