(LeetCode) String to Integer (atoi) (Java)思路讲解及实现

来源:互联网 发布:mm漫画软件下载 编辑:程序博客网 时间:2024/05/16 10:03

题目:Implement atoi to convert a string to an integer. (将字符串数字转换为整数数字)

atoi 即alphanumeric to integer。

解题思路:

1. 首先字符 '0' 对应的整数为48,'9'对应的整数为57.

本题应考虑一下几个步骤:

2. 输入的字符串不为空;

3. 去除空格,用trim()方法;

4. 判断数字的正负('+'或'-');

5. 进行转换;

6. 结果不应超出Integer的边界。

代码实现如下:

static int myAtoi(String str){        if(str==null || str.equals(""))//判断字符串是否为空            return 0;        str = str.trim();//去空格        int i = 0;        char flag = '+';        if(str.charAt(i) == '-')//判断正负        {            flag = '-';            i++;        }else if(str.charAt(i) == '+')        {            flag = '+';            i++;        }        double result =0;        while(i<str.length()&&str.charAt(i)>='0'&&str.charAt(i)<='9'){//计算对应的整数            result = result*10 + (str.charAt(i)-'0');            i++;        }        if(flag=='-')            result = -result;        if(result > Integer.MAX_VALUE){//越界处理            return Integer.MAX_VALUE;        }        else if(result < Integer.MIN_VALUE) {            return Integer.MIN_VALUE;        }        return (int)result;    }

0 0