Cases:
Convert "1234" to the number 1234.
Convert "1234" to a number-1234.
Convert "+1234" to 1234.
Analysis:
Set a label sign=1 first,
A read character, read to the first character to determine whether it is '-' and ' + '; if it is '-' then make the tag sign=-1, and read the character pointer backward one bit, if it is ' + ', then sign does not change, the pointer moves backward one, the newly read word such as ' 1 ', with ' 1 '-' 0 ', the resulting value is the number 1, set the variable num=0, each read to the character converted to a number and num*10 added and assigned to NUM; Finally, NUM is multiplied with sign and returned.
The code is as follows:
#include <stdio.h>
#include <stdlib.h>
int My_atoi (char s[])
{
int num = 0;
int val = 0;
int sign = 1;
while (*s!= ')
{
if (*s = = '-')
{
sign =-1;
s++;
}
else if (*s = = ' + ')
s++;
val = *s-' 0 ';
num = num * + val;
s++;
}
Num *= sign;
return num;
}
int main ()
{
Char str[] = "+1234";
int num = 0;
int Ret=num=my_atoi (str);
printf ("%d\n", ret);
System ("pause");
return 0;
}
Converts a string to the corresponding integer