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.

    别人的代码,很精简,值得学习。

     1 class Solution {
     2 public:
     3     int atoi(const char *str) {
     4         assert(str != NULL);  
     5         while(isspace(*str)) str++;  // remove ' '  
     6         
     7         int sign = (*str == '-') ? -1 : 1;  
     8         if (*str == '-' || *str == '+')    // if can check one char  
     9             str++;  
    10                
    11         int ret = 0;  
    12         while(isdigit(*str))   // is digit  
    13         {  
    14             int digit = *str - '0';  
    15                
    16             if (INT_MAX / 10 >= ret)  
    17                 ret *= 10;  
    18             else  
    19                 return sign == -1 ? INT_MIN : INT_MAX;  
    20                    
    21             if (INT_MAX - digit >= ret)  
    22                 ret += digit;  
    23             else  
    24                 return sign == -1 ? INT_MIN : INT_MAX;  
    25                    
    26             str++;  
    27         }  
    28            
    29         return ret * sign;  
    30     }
    31 };
  • 相关阅读:
    项目三.
    项目二
    项目一.
    第三季-第27课-Shell脚本高级编程
    第三季-第26课-守护进程设计
    第三季-第26课-网络并发服务器设计
    第三季-第25课-UDP通讯程序设计
    刷新页面
    css让超出文字省略号
    css3 背景透明
  • 原文地址:https://www.cnblogs.com/easonliu/p/3631584.html
Copyright © 2011-2022 走看看