【LeetCode 8】字符串转换整数 (atoi)

  1. 题目描述

  2. 要求

    手动实现系统函数atoi的功能
    注意的条件:
    (1)空串
    (2)不合法的字符串,比如"words and 987" "+-12" "+ 32" “      ”等
    ps:
    	确实如dalao所讲,所有的坑只有自己踩进去才会想到
    
  3. 代码

    #include<iostream>
    #include<cstdio>
    #include<cmath>
    #include<vector>
    #include<stack>
    #include<cstring>
    using namespace std;
    
    long long myatoi(string str)
    {
    	int flag = 1;
    	int len = str.length();
    	int count = 0;
    	long long ans = 0;
    	if(str.size() == 0)
    		return 0;
    	int i = 0;
    	while(str[i++] == ' '){
    		count++;
    	}
    	
    	if(str[count] == '+'){
    		if(!(str[count+1] >=  '0' && str[count+1] <='9'))
    			return 0;
    		flag = 1;
    		count++;	
    	}
    	if(str[count] == '-'){
    		if(!(str[count+1] >=  '0' && str[count+1] <='9'))
    			return 0;
    		flag = -1;
    		count++;
    	}	 
    	for(i = count; i < len; ++i)
    	{
    		if(str[count] < '0' || str[count] >'9'){
    			ans = 0;
    			break;
    		}
    		
    		else if(str[i] >= '0' && str[i] <= '9'){
    			ans = ans*10 + (str[i]-'0'); 
    			if(ans*flag <= INT_MIN){
    		        ans = -1 * INT_MIN;
    		        break;
    		    }
    		    else if(ans*flag >= INT_MAX){
    		        ans = INT_MAX;
    		        break;
    		    }
    		}
    		else if(str[i] < '0' || str[i] >'9' || str[i] == '.')
    		{
    			break;
    		}
    	}
    	return ans*flag;
    }
    
    int main()
    {	
    	string str;
    	while(getline(cin,str)){		//getline()可以读取空字符串、空格 
    		int res = myatoi(str); 
    		cout<<res<<endl;	
    	}
    	return 0;	
    } 
    
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值