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 = 12
Output: 2
Explanation:
The binary representation of the number 13 is “1100”.
Therefore, there are two trailing zeros in the 12.
Input: N = -56
Output: 3
Explanation:
The binary representation of the number -56 is “001000”.
Therefore, there are 3 trailing zeros present in -56.
Approach: Follow the steps to solve the problem
- The idea is to use the observation that after calculating XOR of N with N – 1, all the set bit of N left to the rightmost set bit, i.e LSB set bit disappears and the rightmost set bit of N becomes the leftmost set bit of N ^ (N – 1).
- Print the count of bits of a number (N ^ (N – 1)) decremented by 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countTrailingZeroes( int N)
{
int res = log2(N ^ (N - 1));
return res >= 0 ? res : 0;
}
int main()
{
int N = 12;
cout << countTrailingZeroes(N);
return 0;
}
|
Java
import java.io.*;
class GFG {
public static int countTrailingZeroes( int N)
{
int res = N ^ (N - 1 );
return ( int )(Math.log(temp)
/ Math.log( 2 ));
}
public static void main(String[] args)
{
int N = 12 ;
System.out.println(
countTrailingZeroes(N));
}
}
|
Python3
from math import log2
def countTrailingZeroes(N):
res = int (log2(N ^ (N - 1 )))
return res if res > = 0 else 0
if __name__ = = '__main__' :
N = 12
print (countTrailingZeroes(N))
|
C#
using System;
public class GFG{
public static int countTrailingZeroes( int N)
{
int res = ( int )Math.Log(N ^ (N - 1), 2.0);
if (res >= 0)
return res;
else
return 0;
}
static public void Main ()
{
int N = 12;
Console.WriteLine(
countTrailingZeroes(N));
}
}
|
Javascript
<script>
function countTrailingZeroes(N)
{
let res = parseInt(Math.log(N ^ (N - 1)) /
Math.log(2));
return res >= 0 ? res : 0;
}
let N = 12;
document.write(countTrailingZeroes(N));
</script>
|
Time Complexity: O(log(N))
Auxiliary Space: O(1)
Last Updated :
09 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...