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

      

  • 相关阅读:
    net中System.Security.Cryptography 命名空间 下的加密算法
    关于如何生成代码的帮助文档的链接
    Application.EnableVisualStyles();
    VS2010里属性窗口中的生成操作
    把普通的git库变成bare库
    MultiTouch camera controls source code
    android onTouch()与onTouchEvent()的区别
    iOS开发中常见的语句@synthesize obj = _obj 的意义详解
    java nio 快速read大文件
    使用ndk standalone工具链来编译某个平台下的库
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8493055.html
Copyright © 2011-2022 走看看