Mathworks EDG New Grad | OA 2020 | Shortest path to a number

image

My Solution
long numberOfLeadingZeros(long x)
{
    long n=0;
    const unsigned bits=sizeof(x)*8;
    for (int i=1;i<bits;i++)
    {
        if(x<0)
        break;
        n++;
        x<<=1;
    }
    return n;
}
long bitCount(long x)
{
    long n=0;
    while (x){
        n+=x&1;
        x>>=1;
    }
    return n;
}

vector<int> getMinOperations(vector<long> kValues) {
		vector<int> result;
        for (int i=0;i<kValues.size();i++){
            long x =kValues[i];
            result.push_back(bitCount(x)+63-numberOfLeadingZeros(x));
        }
        return result;
}
Comments (6)