算法设计与分析(2) -- String to Integer(难度:Medium)

算法设计与分析(2)


题目:String to Integer (atoi)
https://leetcode.com/problems/string-to-integer-atoi/?tab=Description

问题描述:
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.

算法思路:

如果不考虑任意情况,默认string的字符串值含有数字,则函数非常简单。然后在此基础上分析任意字符串的处理情况。
首先,这里返回的int是32位的,所以先处理任何会超出这个上界(INT32_MAX)或下界(INT32_MIN)的整数,分别取上/下界返回。
然后要考虑字符串含有其它字符的处理:
(1)清除字符串前面的空格;
(2)前面允许出现一次“+”或“-”,但不能重复;
(3)读取完当前的数字字符后,发现下一个字符不是数字,直接返回当前的结果。

代码:

#include<iostream>
#include<string>

using namespace std;

int Myatoi(string str)
{
    int n = str.length(), i = 0;
    int pos = 1;
    long long int num = 0;
    while (str[i] == ' ') i++;
    if (str[i] == '+' || str[i] == '-')
    {
        if (str[i] == '-') pos = -pos;
        i++;
    }

    for (;i < n;i++)
    {
        if (str[i] >= 48 && str[i] <= 57)
        {
            if (num + pos*(str[i] - 48) > INT32_MAX) return INT32_MAX;
            else if (num + pos*(str[i] - 48) < INT32_MIN) return INT32_MIN;
            else num += pos*(str[i] - 48);
        }
        else return num;

        if (str[i + 1] >= 48 && str[i + 1] <= 57)
        {
            if (num * 10 > INT32_MAX) return INT32_MAX;
            else if (num * 10 < INT32_MIN) return INT32_MIN;
            else num *= 10;
        }
        else return num;
    }
    return num;
}

int main() //test
{
    string str = "   -214748.3648";
    int n = Myatoi(str);
    cout << n  << endl;
    return(0);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值