Comparing leading zeros in binary representations of two numbers
Last Updated :
02 Dec, 2023
Given two integer numbers x and y. Compare and print which one of them has more leading zeros using Bitwise operation. If both the no. have the same no. of leading zeros, print “Equal”.
Note:- A leading zero is any 0 digit that comes before the first nonzero digit in the binary notation of the number.
Examples:
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.
Solution 1: The Naive approach is to first find the binary representation of the numbers and then count the no. of leading zeros.
Solution 2: Find largest power of twos smaller than given numbers, and compare these powers of twos to decide answer.
Solution 3: An efficient approach is to bitwise XOR and AND operators.
Case 1: If both have same no. of leading zeros then (x^y) <= (x & y) because same number of leading 0s would cause a 1 at higher position in x & y.
Case 2 : If we do negation of y and do bitwise AND with x, we get a one at higher position than in y when y has more number of leading 0s.
Case 3: Else x has more leading zeros
C++
#include <bits/stdc++.h>
using namespace std;
void LeadingZeros( int x, int y)
{
if ((x ^ y) <= (x & y))
cout << "\nEqual" ;
else if ((x & (~y)) > y)
cout << y;
else
cout << x;
}
int main()
{
int x = 10, y = 16;
LeadingZeros(x, y);
return 0;
}
|
Java
class GFG
{
static void LeadingZeros( int x, int y)
{
if ((x ^ y) <= (x & y))
System.out.print( "\nEqual" );
else if ((x & (~y)) > y)
System.out.print(y);
else
System.out.print(x);
}
public static void main (String[] args)
{
int x = 10 , y = 16 ;
LeadingZeros(x, y);
}
}
|
Python3
def LeadingZeros(x, y):
if ((x ^ y) < = (x & y)):
print ( "Equal" )
elif ((x & (~y)) > y) :
print (y)
else :
print (x)
if __name__ = = '__main__' :
x = 10
y = 16
LeadingZeros(x, y)
|
C#
using System;
class GFG
{
static void LeadingZeros( int x, int y)
{
if ((x ^ y) <= (x & y))
Console.WriteLine( "\nEqual" );
else if ((x & (~y)) > y)
Console.WriteLine(y);
else
Console.WriteLine(x);
}
static public void Main ()
{
int x = 10, y = 16;
LeadingZeros(x, y);
}
}
|
Javascript
<script>
function LeadingZeros(x, y)
{
if ((x ^ y) <= (x & y))
document.write( "<br>Equal" );
else if ((x & (~y)) > y)
document.write(y);
else
document.write(x);
}
let x = 10, y = 16;
LeadingZeros(x, y);
</script>
|
PHP
<?php
function LeadingZeros( $x , $y )
{
if (( $x ^ $y ) <= ( $x & $y ))
echo "\nEqual" ;
else if (( $x & (~ $y )) > $y )
echo $y ;
else
echo $x ;
}
$x = 10;
$y = 16;
LeadingZeros( $x , $y );
?>
|
Time Complexity: O(1)
Space Complexity: O(1)
Approach#2: Using format
Take two integer inputs from the user. Convert the input numbers to 8-bit binary strings using the format() function. Count the number of leading zeros in each binary string using the lstrip() and len() functions. Compare the number of leading zeros of the two binary strings. Print the number which has more leading zeros, or a message saying that both numbers have equal number of leading zeros.
Algorithm
1. Read the two integers num1 and num2 from the user.
2. Convert num1 and num2 to 8-bit binary strings using the format() function.
3. Count the number of leading zeros in bin1 and bin2 using the lstrip() and len() functions.
4. Compare leading_zeros1 and leading_zeros2.
5. If leading_zeros1 is greater than leading_zeros2, print num1 has more leading zeros.
6. If leading_zeros2 is greater than leading_zeros1, print num2 has more leading zeros.
7. If leading_zeros1 is equal to leading_zeros2, print both numbers have equal number of leading zeros.
C++
#include <iostream>
#include <string>
#include <bitset>
int main() {
int num1 = 10;
int num2 = 12;
std::string bin1 = std::bitset<8>(num1).to_string();
std::string bin2 = std::bitset<8>(num2).to_string();
int leading_zeros1 = bin1.find_first_not_of( '0' );
int leading_zeros2 = bin2.find_first_not_of( '0' );
if (leading_zeros1 == leading_zeros2) {
std::cout << "Equal" << std::endl;
} else if (leading_zeros1 < leading_zeros2) {
std::cout << num1 << " has fewer leading zeros." << std::endl;
} else {
std::cout << num2 << " has fewer leading zeros." << std::endl;
}
return 0;
}
|
Java
public class Main {
public static void main(String[] args) {
int num1 = 10 ;
int num2 = 12 ;
String bin1 = String.format( "%8s" , Integer.toBinaryString(num1)).replace( ' ' , '0' );
String bin2 = String.format( "%8s" , Integer.toBinaryString(num2)).replace( ' ' , '0' );
int leadingZeros1 = bin1.length() - bin1.replaceAll( "^0+" , "" ).length();
int leadingZeros2 = bin2.length() - bin2.replaceAll( "^0+" , "" ).length();
if (leadingZeros1 == leadingZeros2) {
System.out.println( "Equal" );
} else if (leadingZeros1 < leadingZeros2) {
System.out.println(num1 + " has fewer leading zeros." );
} else {
System.out.println(num2 + " has fewer leading zeros." );
}
}
}
|
Python3
num1 = 10
num2 = 12
bin1 = format (num1, '08b' )
bin2 = format (num2, '08b' )
leading_zeros1 = len (bin1) - len (bin1.lstrip( '0' ))
leading_zeros2 = len (bin2) - len (bin2.lstrip( '0' ))
if leading_zeros1 > leading_zeros2:
print (num1)
elif leading_zeros2 > leading_zeros1:
print (num2)
else :
print ( "Equal" )
|
C#
using System;
class Program
{
static void Main()
{
int num1 = 10;
int num2 = 12;
string bin1 = Convert.ToString(num1, 2).PadLeft(8, '0' );
string bin2 = Convert.ToString(num2, 2).PadLeft(8, '0' );
int leadingZeros1 = bin1.Length - bin1.TrimStart( '0' ).Length;
int leadingZeros2 = bin2.Length - bin2.TrimStart( '0' ).Length;
if (leadingZeros1 == leadingZeros2)
{
Console.WriteLine( "Equal" );
}
else if (leadingZeros1 < leadingZeros2)
{
Console.WriteLine($ "{num1} has fewer leading zeros." );
}
else
{
Console.WriteLine($ "{num2} has fewer leading zeros." );
}
}
}
|
Javascript
function compareLeadingZeros(num1, num2) {
let bin1 = num1.toString(2).padStart(8, '0' );
let bin2 = num2.toString(2).padStart(8, '0' );
let leadingZeros1 = bin1.length - bin1.trimStart( '0' ).length;
let leadingZeros2 = bin2.length - bin2.trimStart( '0' ).length;
if (leadingZeros1 === leadingZeros2) {
console.log( "Equal" );
} else if (leadingZeros1 < leadingZeros2) {
console.log(`${num1} has fewer leading zeros.`);
} else {
console.log(`${num2} has fewer leading zeros.`);
}
}
let num1 = 10;
let num2 = 12;
compareLeadingZeros(num1, num2);
|
Time Complexity: O(1) because the program executes a fixed number of instructions regardless of the input values. The execution time of the program is constant and does not depend on the input size.
Space Complexity: O(1) because the program uses a fixed amount of memory to store the input variables, binary strings, and variables to count the leading zeros. The amount of memory used by the program does not depend on the input size.
Similar Reads
Number of leading zeros in binary representation of a given number
Given a positive integer N, the task is to find the number of leading zeros in its binary representation.A leading zero is any 0 digit that comes before the first nonzero digit in a number's binary form. Examples: Input : N = 16Output : 27Explanation: As Binary(16) = (0000000000000000000000000001000
10 min read
Longest common substring in binary representation of two numbers
Given two integers n and m. Find the longest contiguous subset in binary representation of both the numbers and their decimal value. Example 1: Input : n = 10, m = 11 Output : 5 Explanation : Binary representation of 10 -> 1010 11 -> 1011 longest common substring in both is 101 and decimal val
7 min read
Length of longest consecutive zeroes in the binary representation of a number.
We have a number N. Determine the length of the longest consecutive 0's in its binary representation. Examples: Input : N = 14 Output : 1 Binary representation of 14 is 1110. There is only one 0 in the binary representation. Input : N = 9 Output : 2 A simple approach is to traverse through all bits
4 min read
Check if binary representations of two numbers are anagram
Given two numbers you are required to check whether they are anagrams of each other or not in binary representation.Examples: Input : a = 8, b = 4 Output : Yes Binary representations of both numbers have same 0s and 1s. Input : a = 4, b = 5 Output : No Simple Approach: Find the Binary Representation
9 min read
Binary representation of a given number
Given an integer n, the task is to print the binary representation of the number. Note: The given number will be maximum of 32 bits, so append 0's to the left if the result string is smaller than 30 length. Examples: Input: n = 2Output: 00000000000000000000000000000010 Input: n = 0Output: 0000000000
6 min read
XOR of two numbers after making length of their binary representations equal
Given two numbers say a and b. Print their XOR after making the lengths of their binary representation equal by adding trailing zeros to the binary representation of smaller one. Examples : Input : a = 13, b = 5 Output : 7 Explanation : Binary representation of 13 is 1101 and of 5 is 101. As the len
7 min read
Number of mismatching bits in the binary representation of two integers
Given two integers(less than 2^31) A and B. The task is to find the number of bits that are different in their binary representation. Examples: Input : A = 12, B = 15 Output : Number of different bits : 2 Explanation: The binary representation of 12 is 1100 and 15 is 1111. So, the number of differen
8 min read
Minimum number of Binary strings to represent a Number
Given a number N. The task is to find the minimum number of binary strings required to represent the given number as the sum of the binary strings.Examples: Input : 131 Output : Minimum Number of binary strings needed: 3 111 10 10 Input : 564 Output :Minimum Number of binary strings needed: 6 111 11
7 min read
Count trailing zeroes present in binary representation of a given number using XOR
Given an integer N, the task is to find the number of trailing zeroes in the binary representation of the given number. Examples: Input: N = 12Output: 2Explanation:The binary representation of the number 13 is "1100".Therefore, there are two trailing zeros in the 12. Input: N = -56Output: 3Explanati
4 min read
Count of N-bit binary numbers without leading zeros
Given an integer N, the task is to find the count of N-bit binary numbers without leading zeros.Examples: Input: N = 2 Output: 2 10 and 11 are the only possible binary numbers.Input: N = 4 Output: 8 Approach: Since the numbers cannot have leading zeros so the left-most bit has to be set to 1. Now fo
2 min read