/*
* Leetcode8. String to Integer (atoi)
* Funtion:Implement atoi to convert a string to an integer.
* Example:
* Author: LKJ
* Date: 2017/3/01
* Hint:
*/
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
class Solution {
public:
int myAtoi(string str) {
int res = 0, sign = 1, i = 0;
while(str[i] == ' '){i++;}
if(str[i]=='-' || str[i]=='+'){
sign = 1 - 2*(str[i++]=='-');
}
while((str[i]>='0')&&(str[i]<='9')){
if((res>2147483647/10)||((res==214748364)&&((str[i]-'0')>7))){
if(sign==1) return 2147483647;
else return -2147483648;
}
res = res*10 + (str[i++]-'0');
}
return sign*res;
}
};
int main(){
string myin = "2147483648";
int myout;
Solution SA;
myout = SA.myAtoi(myin);
cout << myout << endl;
return 0;
}
LeetCode 简单操作 | 8. String to Integer (atoi)
最新推荐文章于 2022-04-19 19:51:34 发布