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 };
  • 相关阅读:
    Populating Next Right Pointers in Each Node I&&II ——II仍然需要认真看看
    MySQL源码分析以及目录结构
    mysql分表的三种方法
    Hadoop学习
    关系型数据库ACID
    九种基本数据类型和它们的封装类
    java中堆和栈的区别
    软件测试-----Graph Coverage作业
    Lab1--关于安装JUnit的简要描述
    动态导入(import)和静态导入(import)的区别
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5843398.html
Copyright © 2011-2022 走看看