zoukankan      html  css  js  c++  java
  • 力扣题解 8th 字符串转换整数 (atoi)

    8th 字符串转换整数 (atoi)

    • 字符串模式匹配

      这种题目极易写出臃肿的代码,我们需要明确具体的条件,并充分考虑细节。(否则会被样例虐爆)

      这里有一个常用的判断溢出条件的方法,在之前的题目中也有出现。

      • 对于正数:

        if(number > Integer.MAX_VALUE / 10 || (number == Integer.MAX_VALUE / 10 && next_index > 7)) return "溢出";

      • 对于负数:

        if(number < Integer.MIN_VALUE / 10 || (number == Integer.MIN_VALUE / 10 && next_index < -8)) return "溢出";

      class Solution {
          public int myAtoi(String str) {
              if(str == null || str.length() == 0) return 0;
              int point = 0;
              boolean isPositive = true;
              int ans = 0;
      
              while (point < str.length() && str.charAt(point) == ' ') {
                  point++;
              }
      
              if (point < str.length() && str.charAt(point) == '+') {
                  point++;
              } else if (point < str.length() && str.charAt(point) == '-') {
                  isPositive = false;
                  point++;
              }
      
              while (point < str.length() && Character.isDigit(str.charAt(point))) {
                  if (ans > Integer.MAX_VALUE / 10 ||
                          (ans == Integer.MAX_VALUE / 10 && str.charAt(point) - '0' > 7)) {
                      return isPositive ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                  }
      
                  ans = ans * 10 + str.charAt(point++) - '0';
              }
      
              return isPositive ? ans : -ans;
          }
      }
      
    • DFA有限状态机

  • 相关阅读:
    python开发学习-day01 (python安装与版本、字符串、字典、运算符、文件)
    js数组中的常用方法总结
    js与jquery常用数组方法总结
    常用原生JS方法总结(兼容性写法)
    左右切换
    改变奇数行颜色
    toogle
    jQuery 表单验证
    css选择器
    两句话帮你彻底记住gdb之eXamining memory
  • 原文地址:https://www.cnblogs.com/fromneptune/p/13266743.html
Copyright © 2011-2022 走看看