给定一个字符串str,如果str符合日常书写的整数形式,并且属于32位整数的范围,返回str所代表的的整数值,否则返回0。
例如:
str="123",返回123。
str="023",返回0。
str="m123",返回0。
str="-23",返回-23。
str="2147483647",返回2147483647。(最大正整数)
str="2147483648",返回0。(溢出)
str=-"2147483649",返回-2147483648。(最小负整数)
思路来自于左程云老师的《《程序员代码面试指南》》
#include <iostream>
#include <string>
using namespace std;
class solution {
public:
int convert(string str) {
if (str == "" || str.size() < 1) {
return 0; // can not convert
}
if (!isValid(str)) {
return 0; // can not convert
}
bool posi = str[0] == '-' ? false : true;
int minq = INT_MIN / 10;
int minr = INT_MIN % 10;
int res = 0;
int cur = 0;
for (int i = posi ? 0 : 1; i < str.size(); i++) {
cur = '0' - str[i];
if ((res < minq) || (res == minq && cur < minr)) {
return 0; // can not convert
}
res = res * 10 + cur;
}
if (posi && res == INT_MIN) {
return 0; // can not convert
}
return posi ? -res : res;
}
bool isValid(string str) {
if (str[0] != '-' && (str[0] < '0' || str[0] > '9')) {
return false;
}
if (str[0] == '-' && (str.size() == 1 || str[1] == '0')) {
return false;
}
if (str[0] == '0' && str.size() > 1) {
return false;
}
for (int i = 1; i < str.size(); i++) {
if (str[i] < '0' || str[i] > '9') {
return false;
}
}
return true;
}
};
void main() {
solution so;
string test1 = "2147483647";
cout << (so.convert(test1)) << endl;
string test2 = "-2147483648";
cout<<(so.convert(test2))<<endl;
string test3 = "2147483648";
cout<<(so.convert(test3))<<endl;
string test4 = "-2147483649";
cout<<(so.convert(test4))<<endl;
string test5 = "-123";
cout<<(so.convert(test5))<<endl;
string test6 = "0123";
cout << (so.convert(test6)) << endl;
string test7 = "1m3";
cout << (so.convert(test7)) << endl;
}