Algo for you own implementation of atoi :) :)
int val = 0;
for each char in the string
val = val *10 + char-48
lets write some code for it :)
int myatoi(char *convetIt)
{
int val = 0;
while(*convetIt)
{
val = (val * 10) + *convetIt - 48;
convetIt++;
}
}
So how it works? lets see how it works
take an example of string "123"
formula : val = (val * 10 ) + *convetIt - 48
val = (0 * 10 ) + '1' - 48 => 0*10 + 49 - 48 = 0 + 1 = 1
val = (1 * 10) + '2' - 48 => 1*10 + 50 - 48 = 10 + 2 = 12
val = (12 * 10 ) + '3' - 48 => 12*10 + 51 - 48 = 120 + 3 = 123
so val contains 123 now :) . so how come '1' '2' '3' is replaced with 49,50,51 ? they are the asci values of these characters ,hence this logic.
There is some efficient way to implement this , lets see if anyone comes up with that method.
Remember it wont take care of the decimal values .
int val = 0;
for each char in the string
val = val *10 + char-48
lets write some code for it :)
int myatoi(char *convetIt)
{
int val = 0;
while(*convetIt)
{
val = (val * 10) + *convetIt - 48;
convetIt++;
}
}
So how it works? lets see how it works
take an example of string "123"
formula : val = (val * 10 ) + *convetIt - 48
val = (0 * 10 ) + '1' - 48 => 0*10 + 49 - 48 = 0 + 1 = 1
val = (1 * 10) + '2' - 48 => 1*10 + 50 - 48 = 10 + 2 = 12
val = (12 * 10 ) + '3' - 48 => 12*10 + 51 - 48 = 120 + 3 = 123
so val contains 123 now :) . so how come '1' '2' '3' is replaced with 49,50,51 ? they are the asci values of these characters ,hence this logic.
There is some efficient way to implement this , lets see if anyone comes up with that method.
Remember it wont take care of the decimal values .
Thanks a lot .. Nice explanation
ReplyDeleteyou welcome !!
Delete