#include<iostream>
#include<string>
#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX - 1)
using namespace std;
class Solution {
public:
int myAtoi(string str) {
//str = trim(str);
int i = 0;
int flag = 0;
int res = 0;
while(i < str.length()){
if( str[i] == '+' && i == 0){
int flag = 1;
i++;
continue;
}
if( str[i] == '-' && i == 0){
int flag = -1;
i++;
continue;
}
if( str[i] < '0' || str[i] > '9' ){
i++;
return 0;
}
if( str[i] >= '0' && str[i] <= '9' ){
res = res*10 + str[i] - '0';
i++;
}
}
if (flag == 1){
res = res;
}
cout << "flag is:"<< flag <<endl;
if (flag == -1){
res = -res;
}
if (res > INT_MAX){
return INT_MAX;
}
if (res < INT_MIN){
return INT_MIN;
}
return (int)res;
}
};
int main(){
Solution so;
string str = "-123";
cout << "str 0 is: " << str[0];
cout << "the res is:" << so.myAtoi(str) << endl;
}
leetcode 8 String to Integer (atoi)
最新推荐文章于 2021-02-26 22:34:04 发布