convertToInt() function

int convertToInt(string s)
{
int ans=0;
int p=1;
for(int i=s.length()-1;i>=0;i–)
{
ans+=(s[i]-‘0’) * p;
p *= 10;
}
return ans;
}

in the for loop why did we subtract ‘0’ from s[i]

1 Like

Hey @anasmir24
if s[i] is ‘6’ it is present in character form in the string, so you need to convert it into int for adding it to the ans variable, and to convert the character to integer, you need to subtract the ASCII value of ‘0’ from it.

1 Like

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.