【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;
}
时间: 2024-08-30 01:49:51

【leetcode】atoi (hard) ★的相关文章

【LeetCode】- String to 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). Y

【LeetCode】Reverse Integer (2 solutions)

Reverse Integer Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 click to show spoilers. Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if you have alread

【leetcode】Generate Parentheses

题目: 给定整数n,返回n对匹配的小括号字符串数组. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 分析: 这种问题的模式是:1)问题的解有多个 ,2)每个解都是由多个有效的 "步骤" 组成的,3)变更以有解的某个或某些"步骤"

【LeetCode】Implement strStr()

Implement strStr() Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 标准KMP算法.可参考下文. http://blog.csdn.net/yaochunnian/article/details/7059486 核心思想在于求出模式串前缀与后缀中重复部分,将重复信息保存在n

【LeetCode】Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 ->

【LeetCode】Pascal&#39;s Triangle

Pascal's Triangle Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 这题别想用通项公式做,n choose m里面的连乘必然溢出,老老实实逐层用定义做. class Solution { public: vector<vector<

【LeetCode】Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. 思路:第一遍正常复制链表,同时用哈希表保存链表中原始节点和新节点的对应关系,第二遍遍历链表的时候,再复制随机域. 这是一种典型的空间换时间的做法,n个节点,需要大小为O(n

【leetcode】Max Points on a Line (python)

给定一个点,除该点之外的其他所有点中,与该点的关系要么是共线,要么就是共点,也就是两点重合. 共线有三种情况:水平共线,垂直共线,倾斜的共线.合并下这三种情况就是斜率存在的共线和斜率不存在的共线. 那么我们的任务就是针对每个点,找出与其共线的这些情况中,共线最多的点的个数. 注意:最终的结果别忘了加上共点的个数. class Solution: def maxPoints(self, points ): if len( points ) <= 1: return len( points ) ma

【LeetCode】 Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6. More practice: If you have figu