亚马逊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 }

转载于:https://www.cnblogs.com/ziyoudefeng/archive/2012/09/15/2686147.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值