zoukankan      html  css  js  c++  java
  • 【LeetCode】008. 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.

    题解:

      1. 跳过开始的所有空格

      2.如果有 '+'、‘-’ ,则存储正负号。

      3.如果不是数字,则直接返回 0

      4.在 3 过程中,溢出条件(前提是 res 还未添加当前遍历的数字 digit): 

        1) res > INT_MAX 

        2)sign == 1 && res == INT_MAX && digit > 7

        3)sign == -1 && res == INT_MIN && digit > 8

     1 class Solution {
     2 public:
     3     int myAtoi(string str) {
     4         int res = 0;
     5         int n = str.size();
     6         int i = 0;
     7         int sign = 1;
     8         while (i < n && str[i] == ' ') ++i;
     9         if (i == n)
    10             return 0;
    11         if (str[i] == '+' || str[i] == '-')
    12             sign = (str[i++] == '-') ? -1 : 1;
    13         while (i < n && str[i] >= '0' && str[i] <= '9') {
    14             int digit = str[i++] - '0';
    15             if (res > INT_MAX / 10 || res == INT_MAX / 10 && digit > 7)
    16                 return sign == 1 ? INT_MAX : INT_MIN;
    17             res  = res * 10 + digit;
    18         }
    19         
    20         return res * sign;
    21     }
    22 };
  • 相关阅读:
    一文看懂Python匿名函数
    Python数据分析库之pandas,你该这么学!No.1
    探究以太坊 2.0 的分叉选择规则
    Plasma 设计综合列表
    从比特币到 Polkadot
    Ethereum Plasma MVP and Plasma Cash
    Java程序员进阶路线-高级java程序员养成
    matlab混合编程向导(vc,vb,.net...)
    matlab混合编程向导(vc,vb,.net...)
    matlab混合编程向导(vc,vb,.net...)
  • 原文地址:https://www.cnblogs.com/Atanisi/p/8644250.html
Copyright © 2011-2022 走看看