How does this code work

int converToString(string s){

int ans = 0;
int p=1;

for( int i = s.length() -1; i >=0; i ++){

ans+=(( s[i] - ‘0’ ) * );
p= p * 10;

}

}

How is this code working.All this code does is convert string to numbers , i.e if we have 022 as string it will convert it to 22. and if we have 32 it will convert it into 32 only.

but how does it work, can you please explain it to me, role of variable p , this is don’t in "DESIGNING STRING TOKENISER " video .

First refer this In convertToInt()
So by s[i]-‘0’ we extract the integer equivalent of each digit.
You have to convert the number into it integer equivalent. In a number there may be digit at ones place,at ten’s place and so on.
So p is the multiplication factor here.For the rightmost digit it will be 1. For the digit at ten’s place, it will be 10 and so on…
So by the line ans+=(( s[i] - ‘0’ ) * p ); you are actually converting the number in string to its integer equivalent. Dry run it with an example to understand well…

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.