把字符串转换成整数(java版)

来源:互联网 发布:自动分辨率软件 编辑:程序博客网 时间:2024/05/20 12:24

【题目描述】将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0

【输入说明】输入一个字符串,包括数字字母符号,可以为空

【输出说明】如果是合法的数值表达则返回该数字,否则返回0

【样例】

输入:
+2147483647
1a33

输出:
2147483647
0


【解题思路1】
//1. 将输入的字符串转换成字符数组。从大下标开始,反向对每个字符逐个处理。
//2. 若当前字符的ASII码在[48~57],注意是闭区间。则代表当前字符是[0~9],继续判断下一个。
//3. 当遍历到下标为0的字符时,需要进行特殊情况的几个判断。包括是否越界,是否是临界值,是否为负号等。

public class Solution {    public int StrToInt(String str) {        if(str==null || str.length() == 0){            return 0;        }        int result = 0;        char[] chs = str.toCharArray();        int len = chs.length;        for(int i=len-1, j=0; i>0; i--, j++){            int c = (int)chs[i];            if(c<48 ||c>57){                return 0;            }else{                result += (c-48)*Math.pow(10, j);            }        }        int c = (int)chs[0];        if(c<=57&&c>=48){            result += (c-48)*Math.pow(10, len-1);        }        if(result<-2147483648 || result>2147483647){            return 0;     //越界,如果真的越界,直接会报错,result本身没办法越界        }else if(str.equals("2147483648")){            if(c == 45){                result = -2147483648;     //边界值            }        }else if(str.equals("-2147483648")){            result = -2147483648;         //边界值        }else{            if(c == 45){                result = -result;         //负号处理            }        }        return result;    }}

【解题思路2】
//1. 先判断首字符是否为负号。
//2. 判断当前字符是否表示数字。
//3. (res << 1) + (res << 3) 即 res*2+res*8=res*10
//4. [0~9]的二进制表示低四位刚好就是[0~9]。 (chs[i] & 0xf)即取低四位值。

public int StrToInt(String str) {        if(str==null || str.length() == 0){            return 0;        }        int n = str.length(), s = 1;        char[] chs = str.toCharArray();        int res = 0;        if(chs[0] == '-') s = -1;        for(int i = (chs[0] ==  '-' || chs[0] == '+') ? 1 : 0; i < n; ++i){            if(!('0' <= chs[i] && chs[i] <= '9')) return 0;            res = (res << 1) + (res << 3) + (chs[i] & 0xf);//res=res*10+str[i]-'0';        }          return (int)res * s;    }
原创粉丝点击