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;
        }
    };
    

      

  • 相关阅读:
    【SSM】Eclipse使用Maven创建Web项目+整合SSM框架(转自:http://www.cnblogs.com/DoubleEggs/p/6243216.html)
    odoo Wkhtmltopdf failed (error code: -11). Memory limit too low or maximum file number of subprocess reached. Message : b''
    odoo 补货规则,当某个位置的产品匹配到多个规则时优先使用序列号最小的规则
    odoo 销售订单确认怎么触发的发货规则
    linux 内核升级
    linux 运维工具之jumpserver
    odoo 关于odoo 的批量拣货
    JIT
    sping+redis实现消息队列的乱码问题
    JVM参数设置
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8493055.html
Copyright © 2011-2022 走看看