LeetCode String to Integer (atoi) 解题报告

  任务是判断可能出现的情况:

1.空格

2.空指针

3.首字符是0

4.首字符是“+”或“-”

5.判断边界条件,上界INT_MAX=2147483647,下届INT_MIN=-2147483648,小心判断

 1 //
 2 //  main.cpp
 3 //  Longest Substring
 4 //
 5 //  Created by Bowie Hsu  on 29/11/21.
 6 //  Copyright (c) 2014年 Bowie Hsu . All rights reserved.
 7 //
 8 
 9 #include <iostream>
10 #include <string>
11 #include <sstream>
12 #include <vector>
13 #include "stdio.h"
14 #include "ctype.h"
15 using namespace std;
16 
17 class Solution {
18 public:
19     int atoi(const char *str)
20     {
21         int ibgn=1;
22         //判断字符串的情况,空格,空指针
23         while(*str==' ')
24             str++;
25         if(*str==0)
26             str++;
27         //str含有负号,输出的int为负
28         if(*str=='-')
29         {
30             ibgn=-1;
31             str++;
32         }
33         else if (*str=='+')
34         {
35             //ibgn=1;
36             str++;
37         }
38          int output=0;
39         while (isdigit(*str))
40         {
41             int i=*str-'0';
42             output=output*10+i;
43             ++str;
44 
45         if (ibgn==1 && output>INT_MAX)
46         {
47             output=2147483647;
48         }
49         else if(ibgn==-1 && output*ibgn<INT_MIN)
50         {
51             output=2147483648;
52         }
53         }
54         return output*ibgn;
55     }
56 };
57 int main()
58 {
59     const char abb='3';
60     const char *input=&abb;
61     int ans;
62     Solution x;
63     ans=x.atoi(input);
64     cout<<ans<<endl;
65     //cout<<"what?"<<endl;
66 
67 }
原文地址:https://www.cnblogs.com/bowiehsu/p/4133020.html