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有限状态机

  • 相关阅读:
    B
    A
    UVA
    马的移动(BFS) 详细注释 一个具有情怀的题目
    JAVA JDK 环境变量配置--简单图解
    linux系统(rpm与deb环境),JAVA JDK的配置
    Jmeter接口测试+压力测试+环境配置+证书导出
    LR访问Https接口
    GitHub linux 提交文件及403错误处理
    random模块写的验证码
  • 原文地址:https://www.cnblogs.com/fromneptune/p/13266743.html
Copyright © 2011-2022 走看看