8. String to Integer (atoi)

本文介绍了一种将字符串转换为整数的有效方法,并详细解释了如何处理各种边界情况,如空格、正负号及非数字字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

解题思路:这道题不能说是一道算法题,应该是道语法题,它的核心点在于让你去考虑各种边界情况,其实就分为3种:首字符是否为空格,是否为+,-号,是否为数字; 下一步呢就是要考虑处理这三种情况的优先级,假设一个合法integer的字符串s,s首字符无论是space,还是 +/-,数字都是合法的,但是如果首字符是数字,那么后面的space,+/-是可以不处理的,所以优先级的话space,+/-是高于数字的,因为只有space和+/-在数字前面时,才需要去考虑;接下来就是判断space和+/-的优先级,如果space在+/-的前面,则需要消除空格,如果是+/-后面有空格,则是不合法的,不用考虑,所以space的优先级最高,需第一个考虑;

代码如下:

class Solution {
public:
    int myAtoi(string str) {
        if (str.size() == 0) return 0;
    
        int i = 0;
	    long int st = 0;
	    char f='+';
	
	    while (isspace(str[i]) != 0) {
		    i++;
	    }
	    if (i == str.size()) return 0;
	
	    if (str[i] == '+' || str[i] == '-') {
		    f = str[i]; i++;
	    }
	
	    while (isdigit(str[i]) != 0) {
		    st = st * 10 + (str[i] - '0');
	        i++;
		    if(st > INT_MAX){
		        if (f == '+'){
			        return INT_MAX;  
			    }else{
			        return INT_MIN; 
			    }
	        }
			
	    }
	    if (f == '+') {
		    return st;
	    }else{
		    return -st;
	    }
    }
};

运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值