Easy c++ solution.using and operation


#1
int Solution::power(string A) 
{
   long long  k = 0;
    int i=0;
    int len = A.size();
    while(i<len)
    {
        k = k*10+(A[i]-'0');
        i++;
    }
    if(k == 1)
        return 0;
    int p = k-1;
    if((k & p) == 0)
        return 1;
    else
        return 0;
}

#3

Can someone explain how this code is working?
how is ‘k’ able to take values greater than ‘long long’?


#4

Obviously it won’t work. And if it is working then there will be loose test case. This code won’t given you any runtime error but when you give some arbitrarily large number then “k” will contain any value from LONG_MIN to LONG_MAX depending on how much overflow has occurred. and depending on this random value this code will give you output. So when you will enter some large number which is actually a power of 2 and can not be fit into long long, this code will definitely give you a wrong result.