只要考虑的详细一点,做出来不是问题!代码仅供参考!
#include<cstdio> #include<iostream> #include<stdlib.h> using namespace std; class Solution { public: int StrToInt(string str) { if(str=="") return 0; int len=str.size(); int cnt=0; int flag=0; int a=0,b=0; while(cnt<len) { if( str[cnt]>='0'&&str[cnt]<='9' ) { if(flag==0) a=a*10+str[cnt]-'0'; else b=b*10+str[cnt]-'0'; } else if(str[cnt]=='+') { if(flag!=0) a=cal(a,flag,b); flag = 1; if(cnt+1==len||str[cnt+1]<'0'||str[cnt+1]>'9') return 0; b=0; } else if(str[cnt]=='-') { if(flag!=0) a=cal(a,flag,b); flag = -1; if(cnt+1==len||str[cnt+1]<'0'||str[cnt+1]>'9') return 0; b=0; } else return 0; cnt++; } if(flag!=0) a=cal(a,flag,b); return a; } int cal(int a,int flag,int b) { if(flag==1) return a+b; if(flag==-1) return a-b; } }; void init() { char st[]="563214789"; char st1[]="545654djbfh6566"; char st2[]=""; char st3[]="0"; char st4[]="-5614"; char st5[]="25-65+50"; printf("atoi:\n"); printf("%d\n",atoi(st)); printf("%d\n",atoi(st1)); printf("%d\n",atoi(st2)); printf("%d\n",atoi(st3)); printf("%d\n",atoi(st4)); printf("%d\n\n",atoi(st5)); } int main() { init(); string st("563214789"); string st1("545654djbfh6566"); string st2(""); string st3("0"); string st4("-5614"); string st5("25-65+50"); Solution so; printf("Solution:\n"); printf("%d\n",so.StrToInt(st)); printf("%d\n",so.StrToInt(st1)); printf("%d\n",so.StrToInt(st2)); printf("%d\n",so.StrToInt(st3)); printf("%d\n",so.StrToInt(st4)); printf("%d\n\n",so.StrToInt(st5)); return 0; }