LeetCode(8)-- String to Integer(atoi)

首先想到C++中的atoi函数,函数为int atoi(const char* a),此处函数输入要求是const char*类型。string转换为const char*可以使用str.c_str()得到一个int类型。
需要注意的特殊情况有:

  • 整数的范围,如果超过这个范围则输出上下界即可。
  • 字符串前面有空格,并不是一开始就是数字

常见的数据类型的范围。其中编程的时候忘记了可以写成INT_MAX,INT_MIN
unsigned int 0~4294967295
int -2147483648~2147483647
unsigned long 0~4294967295
long -2147483648~2147483647
long long的最大值:9223372036854775807
long long的最小值:-9223372036854775808
unsigned long long的最大值:1844674407370955161
__int64的最大值:9223372036854775807
__int64的最小值:-9223372036854775808
unsigned __int64的最大值:18446744073709551615

class Solution {
public:
    int myAtoi(string str) {

    long result = 0;
    int indicator = 1;

      int  i = str.find_first_not_of(' ');  //找到开始的位置
        if(str[i] == '-' || str[i] == '+')  //判断正负号
            indicator = (str[i++] == '-')? -1 : 1;
        while('0'<= str[i] && str[i] <= '9') 
        {
            result = result*10 + (str[i++]-'0');
            if(result*indicator >= INT_MAX) return INT_MAX;
            if(result*indicator <= INT_MIN) return INT_MIN;                
        }
        return result*indicator;

    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值