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 };
  • 相关阅读:
    思科、华为交换机链路聚合(LACP)配置实例
    华为交换机如何批量配置端口
    接口配置stp disable和配置stp edgedport enable有何区别
    上一篇下一篇文章链接添加TITLE属性
    GitHub打不开解决办法
    华为交换机和思科交换机生成树协议对接/替换方案
    vue中key的作用
    网络模块封装
    Typora+PicGo+LskyPro打造舒适写作环境
    C++ 类的静态成员
  • 原文地址:https://www.cnblogs.com/dengeven/p/4009447.html
Copyright © 2011-2022 走看看