LeetCode 8

String to Integer (atoi)

Implement atoi to convert a string to an integer.

 1 /*************************************************************************
 2     > File Name: LeetCode008.c
 3     > Author: Juntaran 
 4     > Mail: Jacinthmail@gmail.com
 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
",sum);
36         return  sum;
37     }else{
38         sum = (sum *= flag) < INT_MIN ? INT_MIN : sum;
39         printf("%d
",sum);
40         return  sum;
41     }
42 
43 }
44 
45 int main(){
46     
47     char* str = "-100.ab";
48     myAtoi(str);
49 }
原文地址:https://www.cnblogs.com/Juntaran/p/5428757.html