Leetcode 8. String to Integer (atoi)( C++版)

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.

思路分析:

将一个字符串转化为整数。考虑输入情况:

  • 输入有空格(若空格在最前面或最后面,忽略空格;若空格在字符中间,比如“  0012 a34”,返回为空格前面的计算结果,即12);
  • 正负数:第一个有效字符为数字或者“+”,是正数。第一个有效字符如果为“-”,是负数。若其他字符为非数字字符,则返回该字符前面的计算结果;

要注意的点:

结果应用long型存储,防止越界。最后转化为int型;

class Solution {
public:
    int myAtoi(string str) {
        if(str.length() == 0) return 0;
        
        long sum = 0;
        bool isPositive = true;//默认为正数
        int i = 0;
        for( ; i < str.length(); ){//过滤最初的空格或者符号位
                if(str[i] == ' '){
                    i ++;
                    continue;
                }
                else if(str[i] == '-'){
                    isPositive = false;
                    i ++;
                    break;
                }
                else if(str[i] == '+'){
                    i ++;
                    break;
                }
                else
                    break;//如果第一个字符为数字,则不做任何动作,进入下面的计算
        }
        
        for( ; i < str.length(); i ++){
           // if(str[i] == ' ' || str[i] == '-' || str[i] == '+' || !isdigit(str[i]) ){//输入不合格
            if(!isdigit(str[i]) ){
                break;
            }
  
            if(isPositive){
                sum = sum * 10 + str[i] - '0';
                if(sum >= INT_MAX) return INT_MAX;
            }
            else{
                sum = sum * 10 - (str[i] - '0');
                if(sum <= INT_MIN) return INT_MIN;
            }
        }
        
        return sum;
    }
};





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值