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

leetcode 8.String to Integer (atoi)

时间:2014-11-08 11:58:04      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   ar   os   使用   sp   for   div   

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

注意点:

1)前缀空格

2)正负号

3)溢出 (可以使用long long int防止溢出)

 1     int atoi(const char *str) 
 2     {
 3         int flag = 1;
 4         int i = 0;
 5         long long int ret = 0;
 6         
 7         if (NULL == str)
 8             return 0;
 9         while ((str[i] != \0) && (str[i] ==  ))
10             i++;
11             
12         if (str[i] == +)
13         {    
14             flag = 1;
15             i++;
16         }
17         else if (str[i] == -)
18         {    
19             flag = -1;
20             i++;
21         }
22         
23         while ((str[i] != \0) && (str[i] >= 0 && str[i] <= 9))
24         {
25             ret = ret * 10 + (str[i] - 0);
26             if ((flag == 1) && (ret * flag > INT_MAX))
27                 return INT_MAX;
28             if ((flag == -1) && (ret * flag < INT_MIN))
29                 return INT_MIN;
30             i++;
31         }
32         return (int)ret * flag;
33     }

 

  

leetcode 8.String to Integer (atoi)

标签:style   blog   color   ar   os   使用   sp   for   div   

原文地址:http://www.cnblogs.com/ym65536/p/4082974.html

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