前言:
这道题,看上去其实挺简单,重点在于边界考虑的问题。
题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
示例1
输入:
+2147483647
1a33
输出:
2147483647
0
题目解析
刚看这道题,我们就能想出这道题该怎么解决。我们从个位开始依次向上相加其实就可以得出问题了。重点是怎么解决这个如果出现不合法的数值该怎查找。这里我想到了用正则表达式,来进行匹配,如果匹配不到,则直接返回0。这里还要注意的一个问题就是,如果数值溢出了,则直接返回0。
还有一种利用try catch 来实现的方法,很巧妙,在这里贴出来,仅供参考。
代码样例
正则表达式匹配
package com.asong.leetcode.StrToInt;
/**
* 把字符串转换成整数
* 将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
* 使用正则匹配
*/
public class Solution1 {
public int StrToInt(String str) {
if(!str.matches("[1-9,+,-]\\d+"))
return 0;
long result = 0;
int index = str.length()-1;
while(index>=0 && str.charAt(index)>='0'&& str.charAt(index)<='9')
{
result = result + (int)Math.pow(10.0,str.length()-1-index) * (str.charAt(index)-'0');
index--;
}
if(str.charAt(0) == '-')
{
result = -result;
}
if(result>Integer.MAX_VALUE && result<Integer.MIN_VALUE)
{
return 0;
}
return (int)result;
}
public static void main(String[] args) {
String str = "123";
Solution1 solution = new Solution1();
int res = solution.StrToInt(str);
System.out.println(res);
}
}
try catch 实现巧妙解法
package com.asong.leetcode.StrToInt;
/**
* 把字符串转换成整数
* 将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
*/
public class Solution {
//通过使用异常抛出 来解决这个问题
public int StrToInt(String str) {
Integer result = 0;
try{
result = new Integer(str);
}catch(NumberFormatException e)
{
}finally{
return result;
}
}
}