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 };
  • 相关阅读:
    .NET中使用Memcached的相关资源整理
    Windows 下的.NET+ Memcached安装
    基于.NET的大型Web站点StackOverflow架构分析(转)
    组建学习型项目团队(转)
    WIN 2003服务器终极安全及问题解决方案
    禁止用户远程登录方法方法
    微信公众平台完整开发教程【转】
    【转】Android 最火的快速开发框架XUtils
    【转】Android 最火框架XUtils之注解机制详解
    android开发Proguard混淆与反射
  • 原文地址:https://www.cnblogs.com/dengeven/p/4009447.html
Copyright © 2011-2022 走看看