题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
示例1
输入
+2147483647
1a33
输出
2147483647
0
法一:使用long
import java.util.Stack;
public class Solution {
public int StrToInt(String str) {
if(str==null||str.length()==0)
return 0;
Stack<Long> stack=new Stack();
char [] chars=str.toCharArray();
int fuhao=1;
int i=0;
if(chars[i]=='+')
i++;
else if(chars[i]=='-'){
fuhao=-1;
i++;
}
for(;i<chars.length;i++){
if(chars[i]>='0'&&chars[i]<='9'){
stack.push((long)chars[i]-(long)'0');
}
else
return 0;
}
Long num=0l;
Long wei=1l;
while(!stack.isEmpty()){
num+=wei*stack.pop();
wei*=10l;
}
num=num*(long)fuhao;
if(num>Integer.MAX_VALUE||num<Integer.MIN_VALUE)
return 0;
return num.intValue();
}
}
法二:不使用long
import java.util.Stack;
public class Solution {
public int StrToInt(String str) {
if(str==null||str.length()==0)
return 0;
Stack<Integer> stack=new Stack();
char [] chars=str.toCharArray();
int fushu=-1;
int i=0;
if(chars[i]=='+')
i++;
else if(chars[i]=='-'){
fushu=1;
i++;
}
for(;i<chars.length;i++){
if(chars[i]>='0'&&chars[i]<='9'){
stack.push((int)chars[i]-(int)'0');
}
else
return 0;
}
int num=0;
int wei=1;
while(!stack.isEmpty()){
num-=wei*stack.pop();//先让num一直是负数,防止溢出
wei*=10;
}
if(num>0||((num==Integer.MIN_VALUE)&&fushu==-1))//当发生溢出或者为正数取不到的负数最小值时
return 0;
return num*fushu;
}
}