zoukankan      html  css  js  c++  java
  • 8. 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.

    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.

    public int MyAtoi(string str) {
            double res = 0;
            bool signPos = true;
            int size = str.Length;
            if(size ==0 ) return 0;
            var digits = new List<char>{'0','1','2','3','4','5','6','7','8','9'};
            int start = 0;
            while(start < size && str[start] == ' ')
            {
                start++;
            }
            //+ - 
            if(start == size) return 0;
            if(str[start] == '-') {signPos = false;start++;}
            else if(str[start] == '+') start++;
            int tempStart = start;
            for(int i = tempStart;i<size;i++)
            {
                if(!digits.Contains(str[i])) break;
                if(i == start && str[i] == '0')
                {
                    start++;
                }
                else
                {
                    res *= 10;
                    res += str[i]-'0';
                }
            }
            res = (signPos)?res:-1*res;
            if(res > Int32.MaxValue) return Int32.MaxValue;
            if(res < Int32.MinValue) return Int32.MinValue;
            return (int)res;
        }
  • 相关阅读:
    ajax的post提交方式和传统的post提交方式哪个更快?
    请问具体到PHP的代码层面,改善高并发的措施有哪些
    TP为什么这个if判断什么都不显示?
    如何用正则匹配这段文本
    七牛上图片总是net::ERR_NAME_NOT_RESOLVED
    该如何来开发这个喜欢的功能呢?
    打包phar文件过大的问题。
    .map(function(item)...)这个是按hashcode自动遍历的,怎么才能按照我想要的顺序遍历呢?
    Java操作Kafka执行不成功
    webkit事件处理
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5873973.html
Copyright © 2011-2022 走看看