String to Integer (atoi)
Implement atoi to convert a string to an integer.
1 /************************************************************************* 2 > File Name: LeetCode8.c 3 > Author: Juntaran 4 > Mail: [email protected] 5 > Created Time: 2016年04月24日 星期日 15时51分05秒 6 ************************************************************************/ 7 8 /************************************************************************* 9 10 Implement atoi to convert a string to an integer. 11 12 ************************************************************************/ 13 14 #include <stdio.h> 15 #include <limits.h> 16 17 int myAtoi(char* str) { 18 19 int flag = 1; 20 long sum = 0; 21 22 while( *str == ‘ ‘ ){ 23 str++; 24 } 25 26 if ( *str == ‘+‘ || *str == ‘-‘ ){ 27 flag = (*str++ == ‘+‘ ? 1 : -1 ); 28 } 29 30 while( isdigit(*str) && sum < INT_MAX ){ 31 sum = 10*sum + (*str++ - ‘0‘); 32 } 33 if( flag == 1 ){ 34 sum = sum > INT_MAX ? INT_MAX : sum; 35 printf("%d\n",sum); 36 return sum; 37 }else{ 38 sum = (sum *= flag) < INT_MIN ? INT_MIN : sum; 39 printf("%d\n",sum); 40 return sum; 41 } 42 43 } 44 45 int main(){ 46 47 char* str = "-100.ab"; 48 myAtoi(str); 49 }
时间: 2024-10-11 19:15:26