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 };
  • 相关阅读:
    JVM -- Full GC触发条件总结以及解决策略
    java实现-图的相关操作
    Integer的intValue()方法
    Java transient关键字
    Redis 单线程模型介绍
    String类的intern()方法 -- 重用String对象,节省内存消耗
    数据库阿里连接池 druid配置详解
    redis 实现发布/订阅模式
    Redis实现队列
    redis 实现分布式锁
  • 原文地址:https://www.cnblogs.com/dengeven/p/4009447.html
Copyright © 2011-2022 走看看