zoukankan      html  css  js  c++  java
  • LeetCode: String to Integer

    Title : 

    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.

    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 optional 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 a valid 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.

    需要考虑的因素有:

    空格,正负号,越界等。这里对于中间出现非数字字符则是直接忽略后面的所有字符串,

    if(!isdigit(c)) break; 
    class Solution {
    public:
    
        bool isdigit(char c){
            if (c >= 48 && c <= 57)
                return true;
            else
                return false;
        }
        int atoi(string str){
            long long  ans = 0,res=1;
            bool flag = false;
            char c;
            for(int i=0;i < str.size() ;i++){
                c = str[i];
                if(!flag && (c==' ' || c=='	' || c=='
    ' || c=='
    ') ) continue;
                if(!flag && (c=='+' || c=='-') ){
                    if(c=='-') res = -1;
                    flag = true;
                    continue;
                }
                if(!flag && isdigit(c)){
                    flag = true;
                }
                if(!isdigit(c)) break;
                ans = ans * 10 + (c-'0');
                //cout<<ans<<' '<<c<<endl;
                if(ans > INT_MAX ){
                    break;
                }
            }
            ans *= res;
            if(ans > INT_MAX) ans = INT_MAX;
            else if (ans < INT_MIN ) ans = INT_MIN;
            return (int)ans;
        }
    };
  • 相关阅读:
    hdu 4638 Group 线段树
    hdu 4635 Strongly connected 强连通分量
    hdu 4604 Deque
    hdu 1000 A + B Problem
    数组相关
    文本文件相关
    硬件电路中VCC,VDD,VEE,VSS有什么区别
    VIPM链接LabVIEW问题
    Touch实现轻扫
    touchesMoved 实现拖拽
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4419102.html
Copyright © 2011-2022 走看看