ITPub博客

首页 > IT职业 > IT生活 > 剑指offer----把字符串转换成整数

剑指offer----把字符串转换成整数

IT生活 作者:smith12us 时间:2021-09-09 09:32:10 0 删除 编辑

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。

这个题目本身不难,关键在于对非法字符检测,空串,正负号,非数字字符,整数溢出等等

一下代码规定:

   非法字符返回0

   +-号连同符号输出

  溢出抛出异常

public class Solution29 {

    public static void main(String[] args) {

        Solution29 solution29 = new Solution29();

        String s1 = "+2147483647";

        String s2 = "1a33";

        System.out.println(solution29.StrToInt(s2));


    }


   

    public int StrToInt_2(String str) {

        //判断字符串是否为空,长度是否为0

        if (str == null || str.length() == 0) {

            return 0;

        }

        int start;

        int tag;//1表示+ 0表示-

        if (str.charAt(0) == '+') {

            start = 1;

            tag = 1;

        } else if (str.charAt(0) == '-') {

            start = 1;

            tag = 0;

        } else {

            start = 0;

            tag = 1;

        }

        long result = 0;

        for (int i = start; i

            char temp = str.charAt(i);

            if (temp >= '0' && temp

                result = result * 10 + (temp - '0');

                if (tag == 1 && result > Integer.MAX_VALUE) throw new RuntimeException("上溢出");

                if (tag == 0 && result

            } else {

                return 0;

            }

        }


        if (tag == 0) {

            return (int) (-1 * result);

        } else {

            return (int) result;

        }

    }


    public int StrToInt(String str) {

        int res = 0;

        try {

            res = Integer.valueOf(str);

        } catch (NumberFormatException e) {

            res = 0;

        }

        return res;

    }



来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3181/viewspace-2804413/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-30

  • 博文量
    80
  • 访问量
    515