String to Integer (atoi)
Implement atoi to convert a string to an integer.
/*************************************************************************
> File Name: LeetCode8.c
> Author: Juntaran
> Mail: Jacinthmail@gmail.com
> Created Time: 2016年04月24日 星期日 15时51分05秒
************************************************************************/
/*************************************************************************
Implement atoi to convert a string to an integer.
************************************************************************/
#include <stdio.h>
#include <limits.h>
int myAtoi(char* str) {
int flag = 1;
long sum = 0;
while( *str == ' ' ){
str++;
}
if ( *str == '+' || *str == '-' ){
flag = (*str++ == '+' ? 1 : -1 );
}
while( isdigit(*str) && sum < INT_MAX ){
sum = 10*sum + (*str++ - '0');
}
if( flag == 1 ){
sum = sum > INT_MAX ? INT_MAX : sum;
printf("%d\n",sum);
return sum;
}else{
sum = (sum *= flag) < INT_MIN ? INT_MIN : sum;
printf("%d\n",sum);
return sum;
}
}
int main(){
char* str = "-100.ab";
myAtoi(str);
}