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 };
  • 相关阅读:
    android 运行时异常捕获
    汇编32位寄存器和地址编号的五种书写形式
    各种进制的乘法表,八进制的加法,和数字的源码你,反码,和补码
    第一个c程序和vs2017 在打开MFC rc文件时找不到rcdll.dl
    asdfasdf
    php如何判断一个字符串是否包含另一个字符串
    php计算时间差/两个时间日期相隔的天数,时,分,秒.
    PHP服务器时间差8小时解决方案
    历年学生作品评论
    第一周例行报告
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5843398.html
Copyright © 2011-2022 走看看