题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
输入:
+2147483647
1a33
输出:
2147483647
0
code
- 这题判断合法数字直接借用了上一题(表示数值的字符串),实际上远没有这么复杂哈
- 数据没有我想的复杂,并没有溢出,也没有e/E
- 应该是可以在判断完符号之后直接用atoi()函数的
class Solution {
public:
bool isIllegalLetter(char ch){//判断合法字母
if(ch=='+'||ch=='-'||ch=='e'||ch=='E'||ch=='.')
return true;
if(ch>='0'&&ch<='9')
return true;
return false;
}
bool isNumeric(string str)
{
int decimalPoint=0;//小数点个数
for(int i=0; str[i]!='\0'; i++){
char ch=str[i];
if(!isIllegalLetter(ch))
return false;
if(ch=='+'||ch=='-'){
if(i>0&&str[i-1]!='e'&&str[i-1]!='E')
return false;
else if(!isdigit(str[i+1])&&str[i+1]!='.')//+-号后面可带小数点
return false;
}
if(ch=='e'||ch=='E'){
if(str[i+1]=='\0')
return false;
else{
for(int j=i+1;str[j]!='\0';j++){
if(str[j]=='.')
return false;
}
}
}
if(ch=='.'){
decimalPoint++;
if(decimalPoint>0)//不含小数点
return false;
}
}
return true;
}
int StrToInt(string str) {
//char*tmp = (char*)str.c_str();
if(!isNumeric(str.c_str()))
return 0;
int flag=1;
int ans=0;
if(str[0]=='+'||str[0]=='-'){
if(str[0]=='-')
flag=-1;
str=str.substr(1);
}
for(int i=0;i<str.size();i++){
int t=str[i]-'0';
ans = ans*10+t;
}
return flag*ans;
}
};
附
string转化为char*
#include <iostream>
using namespace std;
int main()
{
// 1. string对象的dat()方法
string str = "lijiajia";
char*p= (char*)str.data();
cout<<p<<endl;
// 2. string对象的c_str()方法
char*p1 = (char*)str.c_str();
cout<<p1<<endl;
//3. string对象的copy方法
char strtemp[40];
str.copy(strtemp,8,0);
*(strtemp+8) = '\0';
cout<<strtemp<<endl;
system("pause");
return 0;
}
参考链接: