码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 8

时间:2016-04-24 23:13:40      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:

String to Integer (atoi)

Implement atoi to convert a string to an integer.

 

 1 /*************************************************************************
 2     > File Name: LeetCode8.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\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 }

 

LeetCode 8

标签:

原文地址:http://www.cnblogs.com/Juntaran/p/5428757.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!