面试题:不用Java内置函数把String类型转int类型

  面试中遇到一道算法题:不采用java的内置函数,把String类型转换为int类型。现采用两种方法实现(直接上代码):

package com.haiwi.test;

public class AtoiTest {
  public static void main(String[] args) throws Exception {
    String s = "-011134";
    System.out.println("转换前的字符串:" + s);
    System.out.println("atoi1转换后的字符串:" + atoi1(s));
    System.out.println("atoi2转换后的字符串:" + atoi2(s));

  }

  /**
   * 不用java内置函数,将String字符串转换为数字
   * @param s
   * @return
   * @throws Exception 
   */
  public static int atoi1(String s) throws Exception {
    if (s == null || s.length() == 0) {
      throw new Exception("要转换的字符串为空,无法转换!");
    }
    int retInt = 0;
    int[] num = new int[s.length()];
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      switch (c) {
      case '-':
        num[i] = -1;
        break;
      case '0':
        num[i] = 0;
        break;
      case '1':
        num[i] = 1;
        break;
      case '2':
        num[i] = 2;
        break;
      case '3':
        num[i] = 3;
        break;
      case '4':
        num[i] = 4;
        break;
      case '5':
        num[i] = 5;
        break;
      case '6':
        num[i] = 6;
        break;
      case '7':
        num[i] = 7;
        break;
      case '8':
        num[i] = 8;
        break;
      case '9':
        num[i] = 9;
        break;
      default:
        throw new Exception("要转换的字符串格式错误,无法转换!");
      }
    }
    for (int i = 0; i < num.length; i++) {
      if (num[i] < 0 && i > 0) {
        throw new Exception("要转换的字符串格式错误,无法转换!");
      }
      if (num[i] < 0) {
        continue;
      }
      retInt += Math.pow(10, num.length - i - 1) * num[i];
    }
    if (num[0] == -1) {//代表负数
      retInt = -retInt;
    }
    return retInt;
  }
  /**
   * 不用java内置函数,将String字符串转换为数字
   * @param s
   * @return
   * @throws Exception
   */
  public static int atoi2(String s) throws Exception{
    int retInt = 0;
    if (s == null || s.length() == 0) {
      throw new Exception("要转换的字符串为空,无法转换!");
    }
    boolean isNegative = false;
    for (int i = 0; i < s.length(); i++) {
      if (i==0) {
        if(s.charAt(i)=='-'){
          isNegative = true;
          continue;
        }
      }else{
        if(s.charAt(i)>'9' || s.charAt(i)<'0'){
          throw new Exception("要转换的字符串格式错误,无法转换!");
        }
      }
      retInt *=10;
      retInt += s.charAt(i) - '0';
    }
    return isNegative ? -retInt : retInt;
  }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值