Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594

[LeetCode]String to Integer (atoi)-2014.01.08

Posted on 2014-01-11 02:14 Uriel 阅读(66) 评论(0)  编辑 收藏 引用 所属分类: LeetCode
将一个数字串[string]转化为int,主要考察各种奇葩trick有木有考虑
不看提示果断想不起来要判断上下越界的问题...然后像- 1这种中间有空格的是不合法的,正负号后面必须直接接数字,像-12a12这样中间有其他字符的就在中间断开,输出为-12

 1 class Solution {
 2 public:
 3     int atoi(const char *str) {
 4         int i = 0, fg = 1;
 5         int res;
 6         long long tp = 0;
 7         while(str[i] && str[i] == ' ') ++i;
 8         if(str[i] == '-') {
 9             fg = 0;
10             ++i;
11         }
12         if(str[i] == '+') ++i;
13         while(str[i]) {
14             if(str[i] >= '0' && str[i] <= '9') {
15                 tp = tp * 10 + str[i] - '0';
16                 if(fg && tp > (long long)INT_MAX) {
17                     return INT_MAX;
18                 }
19                 if(!fg && tp > (long long)INT_MAX + 1) {
20                     return INT_MIN;
21                 }
22             }
23             else
24                 break;
25             ++i;
26         }
27         if(!fg) tp = -tp;
28         return (int)tp;
29     }
30 };

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理