find the number of trailing zeroes
Given an integer N, the task is to find the number of trailing zeroes in the binary representation of the given number.
Input 1: N = 12
Output 1: 2
Explanation 1: The binary representation of the number 13 is “1100”. Therefore, there are two trailing zeros in the 12.
Input 2: -56
Output 2: 3
Approach 1 : Use Inbuilt function
int trailingZeroCount = Integer.numberOfTrailingZeros(n);
Aprroach 2:
public class codefile{
static int solve(int n){
// Method to count the number of trailing zeros in the binary representation of 'n'
// Initialize count to 0
int count = 0;
// Loop to check each bit from the right (Least Significant Bit)
// Use 'n & 1' to check if the current bit is 0 (last bit)
// Shift the number to the right using >>> (unsigned right shift) to process the next bit
while ((n & 1) == 0) { // If the last bit is 0, continue
count++; // Increment count for each trailing zero
n = n >>> 1; // Perform an unsigned right shift to move to the next bit
}
// Return the total number of trailing zeros found
return count;
}
}
Comments
Post a Comment