zoukankan      html  css  js  c++  java
  • leetcode String to Integer (atoi) 字符串转整数

    Implement atoi to convert a string to an integer.

     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.

    题目:实现字符串转整数

    注意事项:考虑好各种可能的输入(坑);

    public class Solution {
      public int myAtoi(String str) {

        }

    }

    解题感受:题目本身不是特别难,只要找到一个基准,java中是'0'(char)依据输入字符串中的每个字符,与基准之间的差值,确定进制进行相乘累加,判断+,-,思路非常简单,难点在于:

    1.各种极端的边界参数,leetcode的test上有1047个case,估计大部分失败都是在" -+12","-","+","  12a34"之类的corner cases上;

    2.int整数上下边界的处理;

    对于边界,我这里直接用了double进行扩大而后转为int,暂时想不出啊好的处理方法,代码以下:

    public int myAtoi(String str) {

      if (str == null || str.length() == 0) {
        return 0;
      }
      boolean flag_neg = false;
      str = str.trim();
      int len = str.length() - 1;
      double digit = 1, count = 0,res = 0;
      char std = '0';
      while (len >= 0) {
        char c = str.charAt(len);
        if ('-' == c) {
          flag_neg = true;
          count++;
        } else if (c == '+') {
          flag_neg = false;
          count++;
        } else if (c >= '0' && c <= '9') {
          int con = str.charAt(len) - std;
          res += con * digit;
          digit *= 10;
        } else {
          res = 0;
         digit = 1;
        }
        len--;
      }
      res = flag_neg ? -res : res;
      if (res >= Integer.MAX_VALUE) {
        res = Integer.MAX_VALUE;
      } else if (res <= Integer.MIN_VALUE) {
        res = Integer.MIN_VALUE;
      }
      if (count > 1)return 0;
      return (int) res; 

    }

  • 相关阅读:
    ISS6 WEB服务器不能访问 grf 报表模板文件的问题
    c# 读取记事本txt文档到DataTable中
    C# 泛型LIST转DataTable
    sql 查出一张表中重复的所有记录数据
    Coolite中GridPanel真实分页(储存过程方式)
    SQL对Xml字段的操作
    反射和特性 自定义转换datatable为强类型集合
    LINQ TO SQL 并发控制
    AS3 加载文件
    使ASP.NET网站Forms验证可以指定多个登录页面
  • 原文地址:https://www.cnblogs.com/wujunjie/p/5650974.html
Copyright © 2011-2022 走看看