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. has 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.
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
# 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) :
# Driver Code
if __name__ == ‘__main__’:
x = 10
y = 16
# This code is contributed
# by Surendra_Gangwar
Time Complexity: O(1)
Space Complexity: O(1)
- Number of leading zeros in binary representation of a given number
- Check if binary representations of two numbers are anagram
- XOR of two numbers after making length of their binary representations equal
- Count number of trailing zeros in Binary representation of a number using Bitset
- 1 to n bit numbers with no consecutive 1s in binary representation.
- Fibbinary Numbers (No consecutive 1s in binary)
- 1 to n bit numbers with no consecutive 1s in binary representation
- Fibbinary Numbers (No consecutive 1s in binary) - O(1) Approach
- First element greater than or equal to X in prefix sum of N numbers using Binary Lifting
- Meta Binary Search | One-Sided Binary Search
- Gray to Binary and Binary to Gray conversion
- Maximum 0's between two immediate 1's in binary representation
- XOR counts of 0s and 1s in binary representation
- Bitwise AND of N binary strings
- Rotations of a Binary String with Odd Value
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.