LeetCode-8.字符串轉換整數(atoi)

地址:https://leetcode-cn.com/problems/string-to-integer-atoi/

思路:按照題目要求判斷即可

Code:

#include<iostream>
using namespace std;
typedef long long LL;

class Solution {
public:
    int myAtoi(string str) {
        long long res=0;
        int l=0,len=str.length();
        while(l<len&&str[l]==' '){
        	++l;
		}
		int p=1,Min=1<<31,Max=-(Min+1);
		if(l!=len){
			if(str[l]=='+')	p=1,++l;
			else	if(str[l]=='-')	p=-1,++l;
			while(l<len&&str[l]>='0'&&str[l]<='9'){
				res=res*10+str[l++]-'0';
				if(p*res<Min){
					res=Min;	break;
				}else	if(p*res>Max){
					res=Max;	break;
				}
			}
			res*=p;
		}
        return res;
    }
};

int main()
{
	ios::sync_with_stdio(false);
	string str;
	Solution So;
	cin>>str;
	cout<<So.myAtoi(str)<<endl;
	
	return 0;
}

 

發佈了325 篇原創文章 · 獲贊 7 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章