【leetcode】atoi (hard) ★

虽然题目中说是easy, 但是我提交了10遍才过,就算hard吧。

 

主要是很多情况我都没有考虑到。并且有的时候我的规则和答案中的规则不同。

答案的规则:

1.前导空格全部跳过  “      123”  = 123

2.正负号要考虑   “+123” = 123  “-123” = -123

3.数字的前导0要跳过  “-0000123” = “-123”

4.在数字阶段遇到非数字值,数字截断  “-0000 123” = 0   “123a213" = 123

5.没有有效数字,返回0  ”+-123“ = 0

6.数字越界,返回 最大值2147483647 或最小值 -2147483648

 

思路:先用strcpy获取有效的数字部分(先跳过前导空格,获取正负号,截至到非数字部分)

        再判断strcpy长度,为0或只有一个+-号,返回0.  (没有有效数字)

        有有效数字,把获取的数字转换成字符串,strcmp判断是否相同。不同表示数字溢出。

                                                    若输入数字是正数,返回最大值,反之返回最小值。

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <string.h>
using namespace std;

class Solution {
public:
    int atoi(const char *str)
    {
        char scheck[100]; //判断是否溢出
        char strcpy[100];  //输入字符串的有效数字部分
        int ans = 0;
        int i = 0;
        int icpy = 0;

        //去掉前导空格
        while(str[i] == ' ')
        {
            i++;
        }
        if(str[i] == '+' || str[i] == '-')
        {
            strcpy[icpy++] = str[i++];
        }
        //去掉紧跟正负号的前导0
        while(str[i] == '0')
        {
            i++;
        }

        for(;str[i] != '\0'; i++)
        {
            if( '0' <= str[i] && str[i] <= '9')
            {
                ans = ans * 10 + (str[i] - '0');
                strcpy[icpy++] = str[i];
            }
            else
            {
                break;
            }
        }
        strcpy[icpy] = '\0';

        if(strlen(strcpy) == 0)
        {
            return 0;
        }
        else if(strlen(strcpy) == 1 && (strcpy[0] == '+' || strcpy[0] == '-'))
        {
            return 0;
        }


        if(strcpy[0] == '-')
        {
            ans = 0 - ans;
            sprintf(scheck, "%d", ans);
        }
        else if(strcpy[0] == '+')
        {
            scheck[0] = '+';
            sprintf(scheck+1, "%d", ans);
        }
        else
        {
            sprintf(scheck, "%d", ans);
        }


        if(strcmp(scheck, strcpy) != 0)
        {
            if(strcpy[0] == '-')
            {
                ans = -2147483648;
            }
            else
            {
                ans =  2147483647;
            }
        }
        return ans;
    }
};

int main()
{
    Solution s;
    char str[50] = "2147483648";
    int ans = s.atoi(str);
    return 0;
}

 

posted @ 2014-12-02 12:05  匡子语  阅读(288)  评论(0编辑  收藏  举报