Hi少帮主 2017-06-14 09:01 采纳率: 0%
浏览 2273

手写parseInt的实现:要求简单一些,把字符串型的数字转化为真正的数字即可(除Number之外)

手写parseInt的实现:要求简单一些,把字符串型的数字转化为真正的数字即可(除Number之外)

  • 写回答

5条回答 默认 最新

  • 75闪光雷 2017-06-14 09:22
    关注

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println(parseInt("-343"));
    System.out.println(Integer.parseInt("-343"));
    }
    public static int parseInt(String str) throws NumberFormatException{
    int res = 0;
    Pattern p = Pattern.compile("^-?\d+$"); //正则表达式
    Matcher m = p.matcher(str);
    if(!m.matches()){
    throw new NumberFormatException();
    }
    for(int i = str.length() -1 ,j = 0; i > -1; i --, j ++){
    char v = str.charAt(i);
    if(i == 0 && v == '-'){
    res = -res;
    break;
    }
    res += (v - 48) * Math.pow(10, j);
    }
    return res;
    }

    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计