• 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");
    }
  • 相关阅读:
    欧拉回路
    2018 年 ACM-ICPC 焦作站现场赛感受
    3.1 基础-抛小球
    2.2 进阶-禁忌雷炎
    初学Java-循环输入直到文件结束
    1.1 基础-取近似值
    1.2 进阶-对称的二叉树
    LEETCODE
    算法
    算法
  • 原文地址:https://www.cnblogs.com/JeromeHuang/p/4442993.html
Copyright © 2020-2023  润新知