/*
* 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 发布
本文详细介绍了如何实现一个将字符串转换为整数的功能,针对LeetCode上的字符串转整数(atoi)题目提供了解决方案。通过C++代码示例,展示了如何处理字符串中的空白字符、符号位以及数字字符,同时考虑了整数溢出的情况。
533

被折叠的 条评论
为什么被折叠?



