• Leetcode 8. String to Integer (atoi)


    8. String to Integer (atoi)

    • Total Accepted: 120050
    • Total Submissions: 873139
    • Difficulty: Easy

    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 possibe input cases.

    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.

    思路:仿写将字符串转换为数字的转换函数。注意以下4种情况:

    1. 空串

    2. 只包含空格的串

    3. 字符串去除前缀空格以后,剩下字符串的第一序列不是数字。比如字符串“  -asd123”,去掉前缀空格以后是“-asd123”,剩下字符串的第一序列不是数字。

    4. 不满足以上3条,但转换后的数字超出整数范围。

    代码:

     1 class Solution {
     2 public:
     3     int myAtoi(string str) {
     4         int i = 0, sign = 1, sum = 0;
     5         str = str + "end";
     6         while(str[i] == ' ') i++;
     7         if (str[i] == '-' || str[i] == '+'){
     8             sign = (str[i] == '-')?-1:1;
     9             i++;
    10         }else{
    11             sign = 1;
    12         }
    13         while (str[i] >= '0' && str[i] <= '9') {
    14             if (sum > INT_MAX/10 || (sum == INT_MAX/10 && str[i] - '0'>7)){
    15                 if (sign == 1) return INT_MAX;
    16                 return INT_MIN;
    17             }
    18             sum *= 10;
    19             sum += str[i++] - '0';
    20         }
    21         return sum*sign;
    22     }
    23 };
  • 相关阅读:
    HTML+CSS知识点总结
    消灭textarea中的神秘空格
    OAuth2.0
    C# task和timer实现定时操作
    C# 多线程task
    EF的使用
    支付宝支付开发
    Basic Auth
    C#中匿名函数、委托delegate和Action、Func、Expression、还有Lambda的关系和区别
    [转]CodeSite使用小结
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5843398.html
Copyright © 2020-2023  润新知