Leetcode StringToInteger 8

//算法思想:对于一个输入串来说,
//step1:首先判断是不是空格,是空格的话就顺序找下去直到第一个非空格的字符
//step2:对于第一个非空格的字符来说,判断是不是字母,是字母的话此字符串不能转化为数字(⊙o⊙)哦!
//step3: 如果是行结束符的话,就结束啦!
//step3:判断第一个字符是不是正负号,并做标记
//step4: 判断是不是溢出这里根据别人的代码表示超过2的31次方为溢出。2^31-1=2147483647
//解释:为什么是31位数字,有一位用来表示符号啊!(我也真是后反劲/(ㄒoㄒ)/~~)
//step5: 大于最大或小于最小会用最大最小表示,这里用INT_MIN,INT_MAX

//问题出现在我把result设为int类型这是不对得,int占用4字节,32位还有一位符号位,
//我在这了写的2147483649=2^31+1超过了边界都不能存储到result中(因为result是int类型)
//所以将result改long long 类型编程占用8字节的 64位,就可以把数字放进去啦!

#include<iostream>
#include<string>
#define INT_MIN -2147483648
#define INT_MAX 2147483647
using namespace std;

class Solution{
public:
    int myAtoi(string str) {
        bool is_positive = true;
        int index = 0;
        long long result = 0;
        long long long_int_min = INT_MIN;
        long_int_min = 0 - INT_MIN;
        cout<<"INT_MIN: "<<INT_MIN<<endl;
        cout<<"long_int_min: "<<long_int_min<<endl;
        while(str[index] == ' '){
            index++;
            cout<<"***"<<str[index]<<endl;
        }
        //对首字符的处理
        if(str[index] == '\0'){
          // return false;不应该这么写
           return 0;
        }
        //对首字符的处理
        if(str[index] == '-'){
            is_positive = false;
            //这步忘记符号也占用了字符串的位置(⊙o⊙)哦!
            index++;
        }
        else if(str[index] == '+'){
            is_positive = true;
            index++;
        }
        else if(str[index] - '0' >= 0 && str[index] - '0' <= 9){
            is_positive = true;
        }
        else{
            return 0;
        }
        while(str[index] - '0' >= 0 && str[index] - '0' <= 9){
            //cout<<"*** "<<str[index]<<endl;
            int digit = str[index] - '0';
            cout<<"index is : "<<index<<"   result :"<<result<<endl;
            result = result * 10 + digit;

            //没写位数递增晕
            index++;
            //检测条件应该写在循环内判别数值是否出现溢出
            cout<<"result :"<<result<<endl;
            if(result > INT_MAX && is_positive == true){

                return INT_MAX;

            }
            if(result > long_int_min && is_positive == false){
                cout<<"--- "<<"result :"<<result<<endl;
                return INT_MIN;
            }
        }
        if(is_positive == false){
            result = -result;
        }
        return (int)result;
    }
};
int main(){
    Solution s;
    string str;
    int result;
    cout<<"enter your string: "<<endl;
    getline(cin,str);
    result = s.myAtoi(str);
    cout<<result;
    while(1);
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值