【leetcode】String to Integer (atoi)

本文介绍了一个高效的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.


分析:

1) int型溢出

2) 异常输入,如“   -12a3”, "     +222"

3) long long 型溢出


解决方案1:

通过我另一个博客中的atoi函数修改而来,时间复杂度O(n)

尝试实现简单地atoi,atof

运行时间8ms

class Solution {
public:
    int myAtoi(string str) {
        long long intVal = 0; //最后返回的int值  
        int sign = 1;   //1代表正数, -1代表负数  
        int k = 0;
        std::string::iterator it = str.begin();
        //跳过字符串前面的空格  
        while (*it == ' ')  
            it++;  
      
        //取得int值的符号  
        if (*it == '-')  
            sign = -1;  
        if (*it == '-' || *it == '+')  
            it++;  
      
        while (*it >= '0' && *it <= '9' && k <= 10) {  
            //ASCII码中'0'的值是0x30  
            intVal = intVal * 10 + ((int)*it - 0x30);  
            it++;  
            k++;
        }
        
        long long result = sign * intVal;
        if (k >= 10) {
            if(result < INT_MIN) return INT_MIN;
            else if (result > INT_MAX) return INT_MAX;
        } else {
            return result;
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值