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; 

    }

  • 相关阅读:
    121.买卖股票 求最大收益1 Best Time to Buy and Sell Stock
    409.求最长回文串的长度 LongestPalindrome
    202.快乐数 Happy Number
    459.(KMP)求字符串是否由模式重复构成 Repeated Substring Pattern
    326.是否为3的平方根 IsPowerOfThree
    231.是否为2的平方根 IsPowerOfTwo
    461.求两个数字转成二进制后的“汉明距离” Hamming Distance
    206.反转单链表 Reverse Linked List
    448. 数组中缺少的元素 Find All Numbers Disappeared in an Array
    常见表单元素处理
  • 原文地址:https://www.cnblogs.com/wujunjie/p/5650974.html
Copyright © 2011-2022 走看看