【leetcode】8. String to Integer (atoi)

来源:互联网 发布:福建 土豪 知乎 编辑:程序博客网 时间:2024/06/14 03:57

https://leetcode.com/problems/string-to-integer-atoi/#/description

题目是将字符串转成整型数,但是需要考虑多种样例输入。根据多次尝试,总结如下:首先将字符串首尾空格全部去掉;然后取它中从头开始到第一个非法字符(除数字0到9之外的数)之前的串,可以确定的是这个串的形式应该是:+/-xxxx或者是xxx或者直接是+/-。如果是+/-,非法应该返回0;如果这个数超出了int的范围,是正数就返回Integer.MAX_VALUE,负数返回Integer.MIN_VALUE。

public static int myAtoi(String str) {str = str.trim();//去除前后空格if(str.length() == 0)//处理空字符串return 0;if(!(str.charAt(0) >= '0' && str.charAt(0) <= '9' || str.charAt(0) == '+' || str.charAt(0) == '-'))//判断首字符是否非法return 0;for (int i = 1; i < str.length(); i++) {if (!(str.charAt(i) >= '0' && str.charAt(i) <= '9')) {//找到第一个非法字符,截断try {if(str.substring(0, i).equals("+") || str.substring(0, i).equals("-"))//处理正负号之后接一个非法字符return 0;return Integer.parseInt(str.substring(0, i));} catch (Exception e) {//处理超出int表示范围的情况if (str.charAt(0) == '-')//区分正负号return Integer.MIN_VALUE;elsereturn Integer.MAX_VALUE;}}}try{if(str.equals("+") || str.equals("-"))//处理只有正负号的情况return 0;return Integer.parseInt(str);}catch(Exception e){//处理超出int表示范围的情况if(str.charAt(0) == '-')//区分正负号return Integer.MIN_VALUE;elsereturn Integer.MAX_VALUE;}    }


0 0