📌  相关文章
📜  比较两个数字的二进制表示形式中的前导零

📅  最后修改于: 2021-05-25 07:17:42             🧑  作者: Mango

给定两个整数x和y。使用按位运算比较并打印其中一个具有更多前导零。如果两者都没有。有相同的编号的前导零,打印“等于”。
注意:-前导零是该数字的二进制表示形式中第一个非零数字之前的任何0数字。
例子:

Input : 10, 16
Output :10
Explanation: If we represent the no.s using 8 bit only then 
Binary(10) = 00001010
Binary(16) = 00010000
Clearly, 10 has 4 leading zeros and 16 has 3 leading zeros

Input : 10, 12
Output : Equal
Binary(10) = 00001010
Binary(12) = 00001100
Both have equal no. of leading zeros.

解决方案1 :天真的方法是首先找到数字的二进制表示形式,然后计算数字。前导零。
解决方案2:找出小于给定数字的最大2的幂,然后比较这些2的幂以决定答案。
解决方案3:一种有效的方法是按位XOR和AND运算符。

C++
// CPP program to find the number with more
// leading zeroes.
#include 
using namespace std;
 
// Function to compare the no. of leading zeros
void LeadingZeros(int x, int y)
{
    // if both have same no. of leading zeros
    if ((x ^ y) <= (x & y))
        cout << "\nEqual";
 
    // if y has more leading zeros
    else if ((x & (~y)) > y)
        cout << y;
 
    else
        cout << x;
}
 
// Main Function
int main()
{
    int x = 10, y = 16;
    LeadingZeros(x, y);
    return 0;
}


Java
// Java program to find the number
// with more leading zeroes.
class GFG
{
// Function to compare the no.
// of leading zeros
static void LeadingZeros(int x, int y)
{
    // if both have same no. of
    // leading zeros
    if ((x ^ y) <= (x & y))
        System.out.print("\nEqual");
 
    // if y has more leading zeros
    else if ((x & (~y)) > y)
        System.out.print(y);
 
    else
        System.out.print(x);
}
 
// Driver Code
public static void main (String[] args)
{
    int x = 10, y = 16;
    LeadingZeros(x, y);
}
}
 
// This code is contributed by Smitha


Python3
# Python 3 program to find the number
# with more leading zeroes.
 
# Function to compare the no. of
# leading zeros
def LeadingZeros(x, y):
     
    # if both have same no. of
    # leading zeros
    if ((x ^ y) <= (x & y)):
        print("Equal")
 
    # if y has more leading zeros
    elif ((x & (~y)) > y) :
        print(y)
 
    else:
        print(x)
 
# Driver Code
if __name__ == '__main__':
    x = 10
    y = 16
    LeadingZeros(x, y)
 
# This code is contributed
# by Surendra_Gangwar


C#
// C# program to find the number
// with more leading zeroes.
using System;
 
class GFG
{
// Function to compare the no.
// of leading zeros
static void LeadingZeros(int x, int y)
{
    // if both have same no. of
    // leading zeros
    if ((x ^ y) <= (x & y))
        Console.WriteLine("\nEqual");
 
    // if y has more leading zeros
    else if ((x & (~y)) > y)
        Console.WriteLine(y);
 
    else
        Console.WriteLine(x);
}
 
// Driver Code
static public void Main ()
{
    int x = 10, y = 16;
    LeadingZeros(x, y);
}
}
 
// This code is contributed by ajit


PHP
 $y)
        echo $y;
 
    else
        echo $x;
}
 
// Driver Code
$x = 10;
$y = 16;
LeadingZeros($x, $y);
     
// This code is contributed by ajit
?>


Javascript


输出:
10

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