面试题49 把字符串转换成整数

题目描述

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。
 1 class Solution {
 2 public:
 3     enum Status{KValid = 0, KInvalid};
 4     int g = KValid;
 5     
 6     long long StrToIntCore(string str, bool minus){
 7         int num = 0, i = 0;
 8         while (str[i] != '\0'){
 9             if (str[i] >= '0' && str[i] <= '9'){
10                 int flag = minus ? -1 : 1;
11                 num = num * 10 + flag * (str[i] - '0');
12                 if ((!minus && num > 0x7FFFFFFF) || (minus && num < (signed int)0x80000000)){
13                     num = 0;
14                     break;
15                 }
16                 i++;
17             }
18             else{
19                 num = 0;
20                 break;
21             }
22         }
23         if (str[i] == '\0'){
24             g = KValid;
25         }
26         return num;
27     }
28     
29     int StrToInt(string str) {
30         g = KInvalid;
31         int num = 0, i = 0;
32         if (str.length() > 0){
33             bool minus = false;
34             if (str[i] == '+'){
35                 i++;
36             }
37             else if (str[i] == '-'){
38                 i++;
39                 minus = true;
40             }
41             if (str[i] != '\0'){
42                 if (i != 0)
43                     str = str.substr(i, str.length() - 1);
44                 num = StrToIntCore(str, minus);
45             }
46         }
47         return num;
48     }
49 };

 

posted @ 2016-04-07 15:47  早杰  阅读(155)  评论(0编辑  收藏  举报