C++ Solution, common division approach


#1

int Solution::power(string A) {

int n = A.size();
int k = n;
int num = 0;
int j = 0;

if(A=="0"|| A=="1")
{
    return 0;
}
while(A[n-1]!='1' || j!=n-1)
{
    j = 0;
    num = 0;
    if(((A[n-1]-'0')%2)==1)
    {
        return 0;
    }
    while(A[j]=='0')
    {
        j++;
    }
    

    
    for(int i=j;i<n;i++)
    {
        
        num = num*10+(A[i]-'0');
        
        A[i] = (num/2)+'0';
        num = num%2;
        
    }
    
    //cout<<A<<"---";
    
}

return 1;

}


#2

Hi Chahat, a slight optimization,
you don’t need to initialize j=0 everytime inside the while loop, because we can safely assume that, all the later iterations will have more than or equal to the number of 0s in the starting of the string :stuck_out_tongue:


#3

Thanks Pratham! the suggestion seems fair.