zoukankan      html  css  js  c++  java
  • 4.String to Integer (atoi)

    Description:

    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.倘若输入为空(input ""),直接返回0

    2.如果输入为空格,则往后一位寻找数字

    3.如果输入为+或-,则定义一个symbol存储该符号,+号变为1,-号变为-1

    4.如果找到数字:

      由于这是字符型数字,需要转换成int类型,此时可以用str[i]-'0'来转换类型,这条语句实际上是字符型数字减去ascii码

    5.将symbol与结果相乘,并检测是否溢出,然后返回结果

    int myAtoi(string str) {

      if(str=="") return 0;
      long answer = 0;
      int symbol;

      int i = str.find_first_not_of(' ');

      if (str[i] == '-' || str[i]=='+')  {

        symbol = (str[i]=='-')? -1:1; 

        i++;

      }
      
      for (i;str[i]>='0'&&str[i]<='9'; i++) answer = answer * 10 + (str[i]-'0');
      answer = answer * symbol;
      return (answer > INT_MAX ? INT_MAX : (answer < INT_MIN ? INT_MIN : answer));
    }

    但是这题存在一个我暂时不解的问题:

      如果我直接用for循环检测前面是否存在空字符的话,系统提示time limit exceed,必须要用str的自带函数find_first_not_of()才能成功通过

  • 相关阅读:
    J2EE第四周
    J2EE 第三周
    jsf简单入门
    Applrt和Ajax
    hello.java分析
    filter用户例子
    分析LogFilter
    理解session
    关于XML
    企业级应用和互联网应用的区别
  • 原文地址:https://www.cnblogs.com/sarahp/p/6583078.html
Copyright © 2011-2022 走看看