zoukankan      html  css  js  c++  java
  • 【Leetcode】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 class Solution {
     2 public:
     3     int atoi(const char *str) {
     4         bool sign = true;
     5         long long ret = 0;
     6         if (!str) {
     7             return 0;
     8         }
     9         int i = 0;
    10         while (str[i] == ' ') {
    11             ++i;
    12         }
    13         if (str[i] == '+') {
    14             sign = true;
    15             ++i;
    16         } else if (str[i] == '-') {
    17             sign = false;
    18             ++i;
    19         }
    20         
    21         while (str[i] != '') {
    22             if (str[i] >= '0' && str[i] <= '9') {
    23                 ret = ret * 10 + (str[i] - '0');
    24             } else {
    25                 break;
    26             }
    27             ++i;
    28         }
    29        ret = sign ? ret : -ret;
    30        ret = ret > INT_MAX ? INT_MAX : ret;
    31        ret = ret < INT_MIN ? INT_MIN : ret;
    32        return ret;
    33     }
    34 };
  • 相关阅读:
    Android Sensor Test
    [转]Android重力感应开发
    nexus5 root教程
    C# split字符串 依据1个或多个空格
    leetcode
    [ffmpeg 扩展第三方库编译系列] 关于须要用到cmake 创建 mingw32编译环境问题
    JAVA网络爬虫WebCollector深度解析——爬虫内核
    Apache htaccess 重写假设文件存在!
    javascript --- 事件托付
    LeetCode——Populating Next Right Pointers in Each Node II
  • 原文地址:https://www.cnblogs.com/dengeven/p/4009447.html
Copyright © 2011-2022 走看看