亚马逊20120915网上机试第一题:atoi函数

 1 #include <iostream>
 2 
 3 using namespace std;
 4 int toInteger(char string[]);
 5 int main(){
 6     char string[100]={0};
 7     cin>>string;
 8     cout<<toInteger(string)<<endl;
 9     return 0;
10 }
11 
12 int toInteger(char string[])
13 {
14     //Your code is here
15     int ret = 0;
16     bool flag = true;
17     unsigned int idx = 0;
18 
19     char c = string[idx];
20     if (c == '+') {
21         flag = true;
22         ++idx;
23     } else if (c == '-') {
24         flag = false;
25         ++idx;
26     }
27 
28     for (; (c=*(string + idx)) != '\0' && c >= '0' && c <= '9'; ++idx) {
29         if (flag) {
30             int temp = ret * 10 + c - '0';
31             if (ret >= temp) {
32                 return 2147483647;
33             }
34             else {ret = ret * 10 + c - '0';}
35         }
36         else {
37             int temp = ret * 10 + c - '0';
38             if (ret >= temp) {
39                 return -2147483648;
40             }
41             else {ret = ret * 10 + c - '0';}
42         }
43 
44     }
45     return flag ? ret : -ret;
46 }
posted @ 2012-09-15 12:57  ziyoudefeng  阅读(295)  评论(0编辑  收藏  举报