String to Integer (atoi)

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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

// string_to_int.cpp : 定义控制台应用程序的入口点。
//将string转化为int,注意点是考虑到所有可能的输入情况

#include "stdafx.h"
#include<iostream>
using namespace std;

int MyAtoi(string s)
{
    int L = s.size();
    int result = 0;
    //输入为空
    if (L == 0)
    {
        return 0;
    }
    
    
    int k; int flag = 0;
    for (int i = 0; i < L; i++)
    {
        //输入为负数- ,输入+
        if (s[i] == '-'&& result == 0 )
        {
            if (flag == 0)
            {
                flag = -1;
                continue;
            }
            else
                return 0;
        }
        if (s[i] == '+'&&result == 0)
        {
            if (flag == 0)
            {
                flag = 1;
                continue;
            }
            else
                return 0;
        }

        //输入非数字字符
        if ((s[i]>'9' || s[i] < '0')&&s[i]!=' ')
        {
            if (flag >= 0)
                return result;
            else
                return -result;
        }
        else if (s[i] == ' ')
        {
            if (flag == 0&&result ==0)
                continue;
            else
                return result;
        }
        else
        {
            k = s[i] - '0';
            //string转化为int越界
            if (result > INT_MAX / 10 || (result == INT_MAX/10 && k > INT_MAX % 10))
            {
                if (flag >= 0)
                    return INT_MAX;
                else
                    return INT_MIN;
            }
            result = result * 10 + k;
        }
    }
    if (flag >= 0)
        return result;
    else
        return -result;
}

int main(int argc, _TCHAR* argv[])
{
    cout << MyAtoi("123  456");
    return 0;
}
这个题目想的就是特殊输入情况,题目测试用例很全面,但是问题也就随之出现。很多有歧义的例子。这就看个人理解了。当然重点是要考虑到这些方面,至于怎么样处理,那仁者见仁智者见智。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值