49、劍指offer--把字符串轉換成整數
阿新 • • 發佈:2017-06-26
初始化 clas weight cout 處理 劍指offer round -h sta 題目描述
將一個字符串轉換成一個整數,要求不能使用字符串轉換整數的庫函數。 數值為0或者字符串不是一個合法的數值則返回0
輸入描述:
輸入一個字符串,包括數字字母符號,可以為空
輸出描述:
如果是合法的數值表達則返回該數字,否則返回0
輸入例子:
+2147483647 1a33
輸出例子:
2147483647 0
解題思路:本題需要考慮幾個方面
1、如果非法輸入,除了結果輸出0,使用全局g_nStatus來標識(進入函數初始化為不合法,最後合法再置為合法)
2、正負號處理
3、數值越界
1 #include <iostream> 2 usingnamespace std; 3 class Solution { 4 public: 5 enum status {kValid=0,kInvalid}; 6 int g_nStatus = kValid; 7 int StrToInt(string str) { 8 g_nStatus = kInvalid; 9 long long num = 0; 10 const char *cstr = str.c_str(); 11 if(cstr != NULL && *cstr != ‘\0‘) 12 { 13 int minus = 1;//符號 14 if(*cstr == ‘-‘) 15 { 16 minus = -1; 17 cstr++; 18 } 19 else if(*cstr == ‘+‘) 20 { 21 cstr++; 22 } 23 while(*cstr != ‘\0‘)//記得是*cstr 24 { 25 if(*cstr >= ‘0‘ && *cstr <= ‘9‘) 26 { 27 num = num*10 + *cstr-‘0‘; 28 cstr++; 29 //數字越界 30 if(((minus > 0) && (num > 0x7FFFFFFF)) || ((minus <0) && (num< (signed int)0x80000000)))//記住加signed int 31 { 32 33 //g_nStatus = kInvalid; 34 num = 0; 35 break; 36 } 37 } 38 else 39 { 40 //g_nStatus = kInvalid; 41 num = 0; 42 break; 43 } 44 } 45 if(*cstr == ‘\0‘) 46 { 47 g_nStatus = kValid; 48 num = num*minus; 49 } 50 } 51 return (int)num; 52 } 53 54 }; 55 int main() 56 { 57 string s = "-123"; 58 Solution a; 59 int res = a.StrToInt(s); 60 cout<<res<<endl; 61 return 0; 62 }
49、劍指offer--把字符串轉換成整數