题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。
考虑首位有正负号和字符串中可能有错误字符的可能。
考虑首位有正负号和字符串中可能有错误字符的可能。
public int StrToInt(String str) {
if(str == null||str.length() == 0)
return 0;
char[] ch=str.toCharArray();
int num=0;
int flag=1;
for(int i=0;i<ch.length;i++)
{
if(ch[i]<'0'||ch[i]>'9')
{
if(i == 0)
{
if(ch[i] == '+')
continue;
else if(ch[i] == '-')
{
flag=-1;
continue;
}
else
return 0;
}
else
return 0;
}
num=num*10+ch[i]-'0';
}
return num*flag;
}