[leetcode]String to Integer (atoi)

本文深入探讨了LeetCode上关于字符串到整数转换(atoi)的问题,详细分析了其核心逻辑和边界情况处理,包括空格、正负号、非数字字符等。通过实例代码展示了解决方案,并强调了实现过程中的关键细节。

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

题目:https://oj.leetcode.com/problems/string-to-integer-atoi/


题目本身并不难,但是需要细心。考虑到输入中各种可能的情况。

代码:

class Solution {
public:
    int atoi(const char *str) {
        if (str == NULL) return 0;
		long long int res = 0, i;
		bool negative = false;
		bool bad_characters = false;
		for (i = 0; str[i] != '\0' && str[i] == ' '; i++)
			//only white space
		if (str[i] == '\0') return 0;
		
		if (str[i] == '-' || str[i] == '+')
		{
			if (str[i] == '-')   negative = true;
			i++;
		}
		//the first character is not valid numbers
		if (str[i] != '\0' && (str[i] <'0' || str[i]>'9')) return 0;
		while (str[i] != '\0')
		{
			if (str[i] >= '0' && str[i] <= '9')
			{
				res = res * 10 + str[i] - '0';
				if (!negative && res >= INT_MAX)
				{
					return INT_MAX;
				}
				if (negative && -res <= INT_MIN)
				{
					return INT_MIN;
				}
				
			}
			else
			{
				if (negative) return -res;
				return res;
			}
			i++;
		}

		if (negative) return -res;
		return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值