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 };
  • 相关阅读:
    java -> final与static 关键字
    软件技术人员需要对数字的敏感性
    如何对抗放假综合症
    IT传统组织结构及新型扁平化组织
    别人的工作台系列三
    别人的工作台系列二
    外包公司做遗留项目有意思么?
    一些外国网站长时间不响应,点叉才能打开的问题
    别人的工作台系列
    2014年干了什么
  • 原文地址:https://www.cnblogs.com/dengeven/p/4009447.html
Copyright © 2011-2022 走看看