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

    Update (2015-02-10):
    The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

    spoilers alert... click to show requirements for atoi.

    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.

    将字符串转为整数,主要是要考虑到输入的字符串的各种情况。
    Java:
    public class Solution {
        public int myAtoi(String str) {
            if (str.isEmpty()) return 0;
            int sign = 1, base = 0, i = 0, n = str.length();
            while (i < n && str.charAt(i) == ' ') ++i;
            if (str.charAt(i) == '+' || str.charAt(i) == '-') {
                sign = (str.charAt(i++) == '+') ? 1 : -1;
            }
            while (i < n && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)) {
                    return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
                base = 10 * base + (str.charAt(i++) - '0');
            }
            return base * sign;
        }
    }
    

    Python:

    class Solution(object):
        def myAtoi(self, str):
            INT_MAX =  2147483647
            INT_MIN = -2147483648
            result = 0
            
            if not str:
                return result
            
            i = 0
            while i < len(str) and str[i].isspace():
                i += 1
            
            sign = 1
            if str[i] == "+":
                i += 1
            elif str[i] == "-":
                sign = -1
                i += 1
    
            while i < len(str) and '0' <= str[i] <= '9':
                if result > (INT_MAX - int(str[i])) / 10:
                    return INT_MAX if sign > 0 else INT_MIN
                result = result * 10 + int(str[i])
                i += 1
            
            return sign * result
    

    C++:

    class Solution {
    public:
        int myAtoi(string str) {
            if (str.empty()) return 0;
            int sign = 1, base = 0, i = 0, n = str.size();
            while (i < n && str[i] == ' ') ++i;
            if (str[i] == '+' || str[i] == '-') {
                sign = (str[i++] == '+') ? 1 : -1;
            }
            while (i < n && str[i] >= '0' && str[i] <= '9') {
                if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
                    return (sign == 1) ? INT_MAX : INT_MIN;
                }
                base = 10 * base + (str[i++] - '0');
            }
            return base * sign;
        }
    };
    

      

  • 相关阅读:
    几句话总结一个算法之DQN
    几句话总结一个算法之Q-Learning与Sarsa
    几句话总结一个算法之Policy Gradients
    深度图像特征在推荐和广告中的应用(三)
    深度图像特征在推荐和广告中的应用(一)
    Kaggle实战之二分类问题
    Kaggle实战之一回归问题
    Deep Learning 论文解读——Session-based Recommendations with Recurrent Neural Networks
    Scala 中的函数式编程基础(三)
    Scala 中的函数式编程基础(二)
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8493055.html
Copyright © 2011-2022 走看看