字符串转成整形 java

题目大意

    实现一个atoi函数,将字符串转成整形
   要点:考虑所有的输入情况。
 
 解题思路
    前导字符是+或-或者没有,接下来输入的是数字,数字不能        整数能表示的最大或最小数。
  如果超过就返回对应的最小或者最小的值。

public int atoi(String str) {

      if (str == null || str.length() == 0) {
//            throw new NumberFormatException("Invalid input string: " + str);
          return 0;
      }

      // 如果字符串以空格开始
      int start = 0; //从开始找第一个不是空格的数
      boolean positive = true; // 是否为正数默认为true

      if (str.charAt(start) == ' ') {
          while (str.charAt(start) == ' ') {
              start++;
              if (start >= str.length()) { // 输入的全是空格
//                    throw new NumberFormatException("Invalid input string: " + str);
                  return 0;
              }
          }
      }

      if (str.charAt(start) == '-') { // 第一个非空白字符中-
          positive = false;
          start++;
      } else if (str.charAt(start) == '+') {// 第一个非空白字符是+
          start++;
      } else if (str.charAt(start) >= '0' && str.charAt(start) <= '9') { // 第一个非空白字符是数字
          return cal(str, start, true);
      } else { // 其它情况就抛出异常
//            throw new NumberFormatException("Invalid input string: " + str);
          return 0;
      }


      if (start >= str.length()) { // 第一个非空白字符是+或者-但也是最后一个字符
//            throw new NumberFormatException("Invalid input string: " + str);
          return 0;
      }

      if (str.charAt(start) > '9' || str.charAt(start) < '0') { // +或者-后面接的不是数字
//            throw new NumberFormatException("Invalid input string: " + str);
          return 0;
      } else {
          return cal(str, start, positive);
      }
  }

  private int cal(String str, int start, boolean positive) {

      long result = 0;
      while (start < str.length() && str.charAt(start) >= '0' && str.charAt(start) <= '9') {
          result = result * 10 + (str.charAt(start) - '0');

          if (positive) { // 如果是正数
              if (result > Integer.MAX_VALUE) {
//                    throw new NumberFormatException("Invalid input string: " + str);
                  return Integer.MAX_VALUE;
              }

          } else {
              if (-result < Integer.MIN_VALUE) {
//                    throw new NumberFormatException("Invalid input string: " + str);
                  return Integer.MIN_VALUE;
              }
          }

          start++;
      }

      if (positive) {
          return (int) result;
      } else {
          return (int) -result;
      }
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值