zoukankan      html  css  js  c++  java
  • 将字符串转换成数字

    问题叙述性说明:

    Implement atoi to convert a string to an integer.

    解决问题的思路:

    对于一个字符串,需要注意以下几点:

    1、所有的空气过滤器在字符串的开头格字符;

    2、注意数字字符前面的“+”和“-”字符。从而确定数字的正负号;

    3、仅仅处理数字字符,一旦出现非数字字符。马上停止字符串处理,并返回已处理的结果;

    4、返回结果时要注意数字越界的问题。不能大于最大值,不能小于最小值。

    class Solution {
    public:
        int atoi(const char *str) {
            if (str == NULL)
                return 0;
            const char *pCur = str;
            long long  result = 0;
            int flag = 0;/*表示该数是否为负值*/
            while (*pCur == ' ' && *pCur != '')
                pCur++;
            if (*pCur == '') /*字符串中仅仅有空格*/
                return 0;
            if (*pCur == '+')/*处理字符串前面的符号*/
                pCur++;
            else if (*pCur == '-') {
                flag = 1;
                pCur++;
            }
            if (*pCur > '9' || *pCur < '0')/*加减号后面为非法字符,跳出处理*/
                return 0;
            if (*pCur != '')
                result = _atoi_core(pCur, flag);
            return (int)result;
        }
        long long _atoi_core(const char * pCur, int flag) {
            long long result;
            while (*pCur != '') {
                if (*pCur >= '0' && *pCur <= '9') {
                    result = result*10 + *pCur - 48;
                    pCur++;
                } 
                else /*遇到非法字符,跳出处理*/
                    break;
            }
            if (result > 0x7FFFFFFF) {
                if (flag)
                    return INT_MIN;
                else
                    return INT_MAX;
            }
            if (flag)
                result = 0 - result;
            return result;
        }
    };


    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    php多态
    ssl certificate problem: self signed certificate in certificate chain
    test plugin
    open specific port on ubuntu
    junit vs testng
    jersey rest service
    toast master
    use curl to test java webservice
    update folder access
    elk
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4854532.html
Copyright © 2011-2022 走看看