zoukankan      html  css  js  c++  java
  • 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.

    Update (2015-02-10):
    The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

    spoilers alert... click to show requirements for atoi.


    分析:好烦的一道题。自己写了好多次都没AC,果然群众的力量比较大。12ms
     1 class Solution {
     2 public:
     3     int myAtoi(string str) {
     4         long long result = 0;
     5         int sign = 1;
     6         int size = str.length();
     7         int index = 0;
     8         
     9         while(str[index] == ' ' && index < size) index++;
    10         
    11         if(str[index] == '+') index++;
    12         else if(str[index] == '-'){
    13             index++;
    14             sign = -1;
    15         }
    16         
    17         for(; index < size; index++){
    18             if(str[index] < '0' || str[index] > '9') break;
    19             
    20             result = result * 10 + str[index] - '0';
    21             if(result > INT_MAX) return sign == 1 ? INT_MAX : INT_MIN;
    22         }
    23         return (int) sign * result;
    24     }
    25 };
  • 相关阅读:
    基础数据类型
    python2x与python3x区别(30个)更新中。。。
    注释
    常量
    变量
    十、SpringCloud config分布式配置中心
    九、Gateway新一代网关
    八、Hystrix断路器(下)
    八、Hystrix断路器(上)
    七、OpenFeign服务接口调用
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4595470.html
Copyright © 2011-2022 走看看