49、剑指offer--把字符串转换成整数
生活随笔
收集整理的這篇文章主要介紹了
49、剑指offer--把字符串转换成整数
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目描述 將一個(gè)字符串轉(zhuǎn)換成一個(gè)整數(shù),要求不能使用字符串轉(zhuǎn)換整數(shù)的庫(kù)函數(shù)。 數(shù)值為0或者字符串不是一個(gè)合法的數(shù)值則返回0? 輸入描述: 輸入一個(gè)字符串,包括數(shù)字字母符號(hào),可以為空 輸出描述: 如果是合法的數(shù)值表達(dá)則返回該數(shù)字,否則返回0 輸入例子: +2147483647 ??? 1a33 輸出例子: 2147483647 ??? 0 解題思路:本題需要考慮幾個(gè)方面 1、如果非法輸入,除了結(jié)果輸出0,使用全局g_nStatus來(lái)標(biāo)識(shí)(進(jìn)入函數(shù)初始化為不合法,最后合法再置為合法) 2、正負(fù)號(hào)處理 3、數(shù)值越界
1 #include <iostream> 2 using namespace 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;//符號(hào) 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 //數(shù)字越界 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 }
1 #include <iostream> 2 using namespace 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;//符號(hào) 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 //數(shù)字越界 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 }
?
轉(zhuǎn)載于:https://www.cnblogs.com/qqky/p/7082575.html
總結(jié)
以上是生活随笔為你收集整理的49、剑指offer--把字符串转换成整数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 腾讯微加信用卡年费是多少?怎么免年费?
- 下一篇: 交行Y-POWER程序员主题信用卡年费多