JZ-C-49

剑指offer第四十九题:把字符串转换为整数

  1 //============================================================================
  2 // Name        : JZ-C-49.cpp
  3 // Author      : Laughing_Lz
  4 // Version     :
  5 // Copyright   : All Right Reserved
  6 // Description : 把字符串转换为整数
  7 //============================================================================
  8 
  9 #include <iostream>
 10 #include <stdio.h>
 11 #include <stdlib.h>
 12 using namespace std;
 13 
 14 long long StrToIntCore(const char* str, bool minus);
 15 
 16 enum Status {
 17     kValid = 0, kInvalid //此时kInvalid为1,如果没有定义enum变量的需求,枚举变量的值可以省略。在以上形式下,第一个值默认值为0,以下各个分别为上一个值加1。
 18 };
 19 int g_nStatus = kValid;//定义全局变量,反映输入是否合法
 20 
 21 int StrToInt(const char* str) {
 22     g_nStatus = kInvalid;//初始为1:不合法
 23     long long num = 0;//用long long型存储转换的str,实际返回的则是int型★
 24 
 25     if (str != NULL && *str != '') {//考虑空指针NULL或字符串为空"",函数直接返回0,且全局变量g_nStatus为1,不合法
 26         bool minus = false;//考虑正负
 27         if (*str == '+')
 28             str++;
 29         else if (*str == '-') {
 30             str++;
 31             minus = true;
 32         }
 33 
 34         if (*str != '') {
 35             num = StrToIntCore(str, minus);
 36         }
 37     }
 38 
 39     return (int) num;//将long long型num转为int
 40 }
 41 
 42 long long StrToIntCore(const char* digit, bool minus) {
 43     long long num = 0;
 44 
 45     while (*digit != '') {
 46         if (*digit >= '0' && *digit <= '9') {
 47             int flag = minus ? -1 : 1;
 48             num = num * 10 + flag * (*digit - '0');
 49             //考虑溢出
 50             if ((!minus && num > 0x7FFFFFFF) //int所能表示的最大正整数
 51             || (minus && num < (signed int) 0x80000000)) { //int所能表示的最小负整数
 52                 num = 0;
 53                 break;
 54             }
 55 
 56             digit++;
 57         } else {
 58             num = 0;
 59             break;
 60         }
 61     }
 62 
 63     if (*digit == '') {
 64         g_nStatus = kValid;
 65     }
 66 
 67     return num;
 68 }
 69 
 70 // ====================测试代码====================
 71 void Test(char* string) {
 72     int result = StrToInt(string);
 73     if (result == 0 && g_nStatus == kInvalid)
 74         printf("the input %s is invalid.
", string);
 75     else
 76         printf("number for %s is: %d.
", string, result);
 77 }
 78 
 79 int main(int argc, char** argv) {
 80     Test(NULL);
 81 
 82     Test("");
 83 
 84     Test("123");
 85 
 86     Test("+123");
 87 
 88     Test("-123");
 89 
 90     Test("1a33");
 91 
 92     Test("+0");
 93 
 94     Test("-0");
 95 
 96     //有效的最大正整数, 0x7FFFFFFF
 97     Test("+2147483647");
 98 
 99     Test("-2147483647");
100 
101     Test("+2147483648");
102 
103     //有效的最小负整数, 0x80000000
104     Test("-2147483648");
105 
106     Test("+2147483649");
107 
108     Test("-2147483649");
109 
110     Test("+");
111 
112     Test("-");
113 
114     return 0;
115 }
原文地址:https://www.cnblogs.com/Laughing-Lz/p/5624821.html