Hello,

I was trying solve the above problem. I came across a solution in the google:

Code:
// C++ program of number of leading zeros in
// binary representation of a given number
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the no. of leading zeros
int countZeros(unsigned int x)
{
    // Keep shifting x by one until leftmost bit
    // does not become 1.
    int total_bits = sizeof(x) * 8;
    int res = 0;
    while ( !(x & (1 << (total_bits - 1))) )
    {
        x = (x << 1);
        res++;
    }
 
    return res;
}
 
// Main function
int main()
{
    int x = 101;
    cout << countZeros(x);
    return 0;
}
as you can see int variable x in main is cast implicitly to unsigned int. "casting" is platform dependent , will it cause issues.
If I pass negetive number to x, the cast value might be represented as 2s complement of the number. (or whatever format the underlying platform is using and also "bigendian/little endian" might also affect the binary rep. Am i right ? Please kindly comment

I was asked the above Q quite sometime back and just wondering about it yesterday

thanks
Pdk