zoukankan      html  css  js  c++  java
  • 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");
    }
  • 相关阅读:
    ecshop 调用指定分类的推荐,热卖,新品
    ecshop 首页调用指定类产品
    html常用笔记
    ecshop 修改flash图片大小
    ecshop 删除随机版权
    Java Web(一) Servlet详解!!
    Git使用总结
    git clone命令使用
    Lucene学习总结之四:Lucene索引过程分析
    Lucene学习总结之二:Lucene的总体架构
  • 原文地址:https://www.cnblogs.com/JeromeHuang/p/4442993.html
Copyright © 2011-2022 走看看