给定整数中匹配设置和未设置位的计数。
两个整数X和Y的任务是通过不考虑二进制形式中较大数字的最左边设置位之后的任何前导零来找到在其二进制表示中相同的位数。
例子:
Input: X = 10, Y = 6
Output: 2
Explanation: The binary representation of 10 is 1010 and 6 is 0110. So, the number of same bits are 2.
Input : X = 3, Y = 16
Output : 2
方法:
直觉:
Calculate least significant bit (LSB) by using (i % 2), where i is any integer and Check if the least significant bit (LSB) of the given integer X, Y are same or not. If same then, increment the answer and right shift the both integer by 1 for checking the LSB are same or not for next bit.
算法:
- 继续执行以下步骤,直到X或Y不是0 。
- 通过X % 2和Y % 2计算给定整数X和Y的LSB ,并检查两者是否相同。
- 如果相同,则增加答案
- 将两个给定的整数右移1
- 通过X % 2和Y % 2计算给定整数X和Y的LSB ,并检查两者是否相同。
下面是上述方法的实现:
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)