[C++][Power of 2] divide and check recursively


#1

It seems test cases for this problem do not involve strings that start with 0.
ex: 00004
The below code handles these conditions too.

string divby2(string &A) {
    string res = "";
    int curEle = 0;
    for(int i=0; i<A.length(); i++) {
        curEle += (A[i]-'0');
        res += (curEle/2 + '0');
        curEle = (curEle%2)*10;
    }
    return res;
}
int Solution::power(string A) {
    int i=0, len = A.length();
    while( i < len && A[i] == '0' ) i++;    // skip initial 0's
    A = A.substr(i);
    len = A.length();
    if(len == 0)                return false;
    if(len == 1 and (A[0]-'0')%2 == 0) {               // single digit and power of 2
        return (__builtin_popcount(A[0]-'0') == 1);
    }
    if((A[len-1] - '0') % 2)                return false;   // last digit odd
    return power(divby2(A));
}


#2

i think this won’t pass the test case for A=6, as the condition :
if(len == 1 &&(A[0]-‘0’)%2 == 0) will return true.

correct me if i’m wrong or missing something


#3

Hi,

Thanks for pointing it. You are correct. I missed.
It would also have failed for input “0”.

I have updated the code now.