博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 8:String to integer(atoi)
阅读量:5168 次
发布时间:2019-06-13

本文共 2009 字,大约阅读时间需要 6 分钟。

题目原文:

  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.

  spoilers alert...click to show requirements for atoi.

  Requirements for atoi:

  The function first discards as many whitespace characters as necessary until the first non-whitespace character is found.Then,starting from this character,takes an opthion initial plus or minus sign followed by as many numerical digits as possible,and interprets them as a numerical value.The string can contain additional characters after those that form the integral number,which are ignored and have no effect on the behavior of this function.

  if the first sequence of non-whitespace characters in str is not avalid integral number,or if no such sequence exists because either str is empty or it contains only whitespace characters,no conversion is performed.

  if no valid conversion could be performed,a zero value is returned.if the correct value is out of the range of representable values,INT_MAX(2147483647)or INT_MIN(-2147483648)is returned.

  题意:实现atoi

  数字开头可能有空格

  有符号

  中间有字母处理字母之前的数字

  比较大小的话用longlong就没问题了

  解答:

  class solution

{
public:
    int atoi(const char* str)
    {
        int num = 0;
        int sign = 1;
        const int n = strlen(str);
        int i = 0;
        while (str[i] == ' '&&i < n)
            i++;
        if (str[i] == '+')   //判断正负号
            i++;
        if (str[i] == '-')
        {
            sign = -1;
            i++;
        }
        for (; i < n; i++)
        {
            if (str[i]<'0' || str[i]>'9')
                break;
            if (num>INT_MAX / 10 || (num == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10))
            {
                return sign == -1 ? INT_MIN : INT_MAX;
            }
            num = num * 10 + str[i] - '0';
        }
        return num*sign;
    }
};

 注意:在写的时候会出现C4146错误,不妨将#define INT_MIN -2147483648写成#define INT_MIN (-2147483647-1).(具体原因是跟数据存储有关,这里不再探究)

转载于:https://www.cnblogs.com/qingjiaowoxiaoxioashou/p/6397792.html

你可能感兴趣的文章
自动分割mp3等音频视频文件的脚本
查看>>
判断字符串是否为空的注意事项
查看>>
布兰诗歌
查看>>
js编码
查看>>
Pycharm Error loading package list:Status: 403错误解决方法
查看>>
steps/train_sat.sh
查看>>
转:Linux设备树(Device Tree)机制
查看>>
iOS 组件化
查看>>
(转)Tomcat 8 安装和配置、优化
查看>>
(转)Linxu磁盘体系知识介绍及磁盘介绍
查看>>
命令ord
查看>>
Sharepoint 2013搜索服务配置总结(实战)
查看>>
博客盈利请先考虑这七点
查看>>
使用 XMLBeans 进行编程
查看>>
写接口请求类型为get或post的时,参数定义的几种方式,如何用注解(原创)--雷锋...
查看>>
【OpenJ_Bailian - 2287】Tian Ji -- The Horse Racing (贪心)
查看>>
Java网络编程--socket服务器端与客户端讲解
查看>>
List_统计输入数值的各种值
查看>>
学习笔记-KMP算法
查看>>
Timer-triggered memory-to-memory DMA transfer demonstrator
查看>>