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

      

  • 相关阅读:
    5 数组 Swift/Object-C ——《Swift3.0从入门到出家》
    4 字符串 Swift/Objective -C ——《Swift3.0从入门到出家》
    3 循环语句——《Swift3.0从入门到出家》
    2 分支语句——《Swift3.0 从入门到出家》
    windows环境下安装epress框架的问题解决方法
    关于rem的使用和less编译工具考拉
    实例了解js面向对象的封装和继承等特点
    CSS3弹性盒模型新版和老版写法差异
    canvas实例:旋转缩放的方块
    用canvas的arc绘制时钟
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8493055.html
Copyright © 2011-2022 走看看