zoukankan      html  css  js  c++  java
  • LeetCode题解(8)--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.

    把字符串转化成整数,需要考虑全面(不看spoilers)。几种特殊情况:

    1.有或者没有符号位。

    2.先有很多空格。(这个有点坑,没想到)

    3.字符串中出现非数字字符。(我直接认为输入错误return 0,但这道题是把它看做终止符)

    4.转化的整数overflow。(存在long long里,然后看overflow没有。我overflow直接return 0,但这道题是截取最大能表达的数)

    PS: 应该尝试用条件表达式简化代码。

    自己的AC代码:

     1 class Solution {
     2 public:
     3     int myAtoi(string str) {
     4         long long x=0;
     5         int i,flag=1,begin=0,n=str.size();
     6         for(i=0;i<n;i++){
     7             if(str[i]!=' ')
     8                 break;
     9         }
    10         begin=i;
    11         if(str[begin]=='-'||str[begin]=='+'){
    12             if(str[begin]=='-')
    13                 flag=-1;
    14             begin++;
    15         } 
    16         for(i=begin;i<n;i++){
    17             if(isdigit(str[i])==1){
    18                 x= 10*x+str[i]-'0';
    19                 if(flag==1 && x>INT_MAX) 
    20                     return INT_MAX;
    21                 else if(flag==-1 && -x<INT_MIN)
    22                     return INT_MIN;
    23             }else
    24                 break;
    25         }
    26         x=flag*x;
    27         return x;
    28     }
    29 };
  • 相关阅读:
    Oracle数据库实例的启动及关闭
    SCJP之赋值
    fileupload组件之上传与下载的页面
    commons-fileupload-1.2.1.jar 插件上传与下载
    SCJP读书之知识点:
    filter
    抽象abstract
    搞定导致CPU爆满的“罪魁祸首”
    优化一个小时不出结果的SQL
    最具戏剧性的分析诊断案例——十分钟锁定数据库性能“元凶”
  • 原文地址:https://www.cnblogs.com/aezero/p/4490694.html
Copyright © 2011-2022 走看看