• String to Integer (atoi)


    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.

    边界条件太多,题目也没i说清楚,都是根据测试数据修改程序……也算过了

    Runtime: 15 ms

    #include <stdio.h>
    #include <stdlib.h>
    #include <string>
    using namespace std;
    
    class Solution {
    public:
        int myAtoi(string str) {
            double num = 0;
            bool isPositive = true;
            if (str=="")
                return 0;
            int i = 0;
            while (str[i] == ' ')
                i++;
            if (str[i] == '-'){
                isPositive = false;
                i++;
                if (str[i] == '+'||str[i]=='-'){
                    return 0;
                }
            }
            if (str[i] == '+'){
                i++;
                if (str[i] == '+' || str[i] == '-'){
                    return 0;
                }
            }
        
            while (i <str.length()&&str[i]>='0'&&str[i]<='9'){
                num = num * 10 + (str[i]-'0');
                i++;
            }
            if (isPositive == false){
                num = num*-1;
            }
            if (num > INT_MAX)
                return INT_MAX;
            else if (num < INT_MIN)
                return INT_MIN;
            else
                return num;
        }
    };
    
    int main(){
        Solution solution;
        printf("%d", solution.myAtoi("    -123"));
        system("pause");
    }
  • 相关阅读:
    SpringBoot学习历程
    日期和时间库Joda Time
    apache commons validator
    apache commons fileupload
    apache commons io
    apache commons compress
    apache commons codec
    apache commons email
    Http协议介绍
    Java原生Socket API
  • 原文地址:https://www.cnblogs.com/JeromeHuang/p/4442993.html
Copyright © 2020-2023  润新知