Intuitive approach without stold (WITH EXPLANATION)


#1

If you, like me, weren’t aware of the function stold, - this is a slightly lengthy, but intuitive approach to the problem. The explanation is detailed:-

int Solution::power(string A) {

int n = A.size();

//If last element is odd, return 0;
if(A[n-1]%2==1)
return 0;

string B="";
int val=0,c=0;

while(1)
{
    //Clear new string (the value of current string value divided by 2
    // would be in this new string)
    
    B.clear();
    for(int i=0; i<A.size(); i++)
    {
     
        if(A[i]-48==0)
        {
            if(c==0)
            val=0;
            if(c==10)
            val=5;
            
            c=0;
        }
       else if((A[i]-48)%2==0)
       {
          val=(A[i]-48+c)/2; 
          c=0;
       }
       else if((A[i]-48)%2==1)
       {
            
           val=(A[i]-48+c)/2;
           //If the current element is odd,
           //We add the next element by 10 and
           //follow the same procedure.
           c=10;
       }
       // If the first element when divided by 2 is zero,
       //we don't add it to the new string.
       if(B.empty() && val==0)
       continue;
       
     B.push_back((char)(val+48));
    }

    A.clear();
    A=B;

    //Final Condition - If there's a single element and size=1, that means the 
    //original number was a power of 2.
    if(A.size()==1 && A[0]-48==1)
    return 1;
    
    //If at any point the last element is odd, and the size is greater than 1,
    //original number is not a power of 2.
    if((A[A.size()-1]-48)%2==1)
    return 0;
}

return 1;
}
;