zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    【转】C#中的虚方法
    【转】ASP.NET 2.0中Page事件的执行顺序
    OWC ChartSpace控件的使用
    Ext对基本类型的扩展
    OWC PivotTable的使用方法
    .net中线程同步的典型场景和问题(1)
    python中使用汉字
    如何取消后台线程的执行
    yaffs2根文件系统的构建过程
    Fuck self.delegate = self
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5843398.html
Copyright © 2011-2022 走看看