2019-09-09[剑指offer-]把字符串转换成整数
2019-11-15 本文已影响0人
Coding破耳
题目描述
将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
输入描述:
输入一个字符串,包括数字字母符号,可以为空</pre>
输出描述:
如果是合法的数值表达则返回该数字,否则返回0</pre>
示例1
输入
+2147483647
1a33
输出
2147483647
0
解法:
class Solution {
public:
int StrToInt(string str) {
if(str == "")
{
return 0;
}
int length = str.length();
bool bflag = true;
bool bstartnum = false;
list<int> st;
for(int i = 0; i < length; ++i)
{
char ch = str[i];
if(!bstartnum)
{
if(ch == '+')
{
continue;
}
else if(ch == '-')
{
bflag = false;
continue;
}
else if(ch <= '9' && ch >= '0')
{
bstartnum = true;
st.push_back(ch-'0');
continue;
}
else
{
return 0;
}
}
else
{
if(ch <= '9' && ch >= '0')
{
st.push_back(ch-'0');
}
else
{
return 0;
}
}
}
if(st.size() == 0)
{
return 0;
}
int result = 0;
list<int>::iterator iter = st.begin();
while(iter != st.end())
{
result = result*10 + (*iter);
iter++;
}
if(!bflag)
{
result = -1 * result;
}
return result;
}
};