zoukankan      html  css  js  c++  java
  • [LeetCode]String to Integer (atoi)

    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.

    题目是Easy的题目,考虑的cases比较多。

    各种没考虑到的情况,根据报错的case改代码就行了。

     1 class Solution {
     2 public:
     3     int myAtoi(string str) {
     4         if(str.length()==0) return 0;
     5         int result;
     6         long long temp=0;
     7         int flag=0;
     8         //正负号标志
     9         int sign=0;
    10         //是否已存在+-号,避免"-+86"类似这种出现
    11         int before_space=0;
    12         //空格前是否有数字标志,有数字返回数值,没数字continue
    13         for(int i=0;i<str.length();i++)
    14         {
    15             if(str[i]==' ')
    16             {
    17                 if(before_space==0) continue;
    18                 else break;
    19             }
    20             if((str[i]=='-')&&(sign==0))
    21             {
    22                 flag=1;
    23                 sign=1;
    24                 before_space=1;
    25             }
    26             else if((str[i]=='+')&&(sign==0))
    27             {
    28                 flag=0;
    29                 sign=1;
    30                 before_space=1;
    31             }
    32             else
    33             {
    34                 before_space=1;
    35                 if (str[i]<'0'||str[i]>'9')
    36                 {
    37                     if(str[i]>='a'&&str[i]<='z')
    38                     {
    39                         break;
    40                     }
    41                     else 
    42                     {
    43                         return 0;
    44                     }
    45                 }
    46                 int number = str[i]-'0';
    47                 if(number==0&&temp==0)
    48                 {
    49                     continue;
    50                 }
    51                 temp = temp*10+number;
    52                 if((temp>INT_MAX)&&(flag==0)) return INT_MAX;
    53                 else if(((temp-1)>INT_MAX)&&(flag==1)) return INT_MIN;
    54             }
    55         }
    56         if(flag==1)
    57         {
    58             temp=-1*temp;
    59         }
    60         result=(int)temp;
    61         return result;
    62     }
    63 };
     
  • 相关阅读:
    You can’t access this shared folder because your organization’s security policies block unauthenticated guest access
    iOS 程序退出之后
    给网站得标签头加上小图标
    ios外界蓝牙适配
    JavaScript&jquery判断下载地址是否可用,同时判断浏览器是否禁用弹窗
    GCD初级使用
    find与xargs
    sed命令详解
    shell变量详解
    date命令详解
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4740324.html
Copyright © 2011-2022 走看看