//算法思想:对于一个输入串来说,
//step1:首先判断是不是空格,是空格的话就顺序找下去直到第一个非空格的字符
//step2:对于第一个非空格的字符来说,判断是不是字母,是字母的话此字符串不能转化为数字(⊙o⊙)哦!
//step3: 如果是行结束符的话,就结束啦!
//step3:判断第一个字符是不是正负号,并做标记
//step4: 判断是不是溢出这里根据别人的代码表示超过2的31次方为溢出。2^31-1=2147483647
//解释:为什么是31位数字,有一位用来表示符号啊!(我也真是后反劲/(ㄒoㄒ)/~~)
//step5: 大于最大或小于最小会用最大最小表示,这里用INT_MIN,INT_MAX
//问题出现在我把result设为int类型这是不对得,int占用4字节,32位还有一位符号位,
//我在这了写的2147483649=2^31+1超过了边界都不能存储到result中(因为result是int类型)
//所以将result改long long 类型编程占用8字节的 64位,就可以把数字放进去啦!
#include<iostream>
#include<string>
#define INT_MIN -2147483648
#define INT_MAX 2147483647
using namespace std;
class Solution{
public:
int myAtoi(string str) {
bool is_positive = true;
int index = 0;
long long result = 0;
long long long_int_min = INT_MIN;
long_int_min = 0 - INT_MIN;
cout<<"INT_MIN: "<<INT_MIN<<endl;
cout<<"long_int_min: "<<long_int_min<<endl;
while(str[index] == ' '){
index++;
cout<<"***"<<str[index]<<endl;
}
//对首字符的处理
if(str[index] == '\0'){
// return false;不应该这么写
return 0;
}
//对首字符的处理
if(str[index] == '-'){
is_positive = false;
//这步忘记符号也占用了字符串的位置(⊙o⊙)哦!
index++;
}
else if(str[index] == '+'){
is_positive = true;
index++;
}
else if(str[index] - '0' >= 0 && str[index] - '0' <= 9){
is_positive = true;
}
else{
return 0;
}
while(str[index] - '0' >= 0 && str[index] - '0' <= 9){
//cout<<"*** "<<str[index]<<endl;
int digit = str[index] - '0';
cout<<"index is : "<<index<<" result :"<<result<<endl;
result = result * 10 + digit;
//没写位数递增晕
index++;
//检测条件应该写在循环内判别数值是否出现溢出
cout<<"result :"<<result<<endl;
if(result > INT_MAX && is_positive == true){
return INT_MAX;
}
if(result > long_int_min && is_positive == false){
cout<<"--- "<<"result :"<<result<<endl;
return INT_MIN;
}
}
if(is_positive == false){
result = -result;
}
return (int)result;
}
};
int main(){
Solution s;
string str;
int result;
cout<<"enter your string: "<<endl;
getline(cin,str);
result = s.myAtoi(str);
cout<<result;
while(1);
return 0;
}
Leetcode StringToInteger 8
最新推荐文章于 2019-04-11 13:20:09 发布