这题的关键就是判断字符串是否为数字和把字符串转成数字。
判断字符串是否为数字
C++ 中,0 到 9 的 ASCII 码是连续的,所以只需要遍历字符串中的每个字符,判断字符是否都大于等于 0 且小于等于 9 即可。
bool isd(string a){
for(char ch:a){//遍历每个字符
if(ch<'0'||ch>'9') return 0;//不符合条件,直接返回不对
}
return 1;
}把字符串转成数字
按照从前往后的顺序遍历字符串,遍历到一个字符后把当前的结果乘十(整体前移一位),再加上这个字符减 0 即可。
int sti(string a){
int ans=0;
for(int i=0;i<a.size();i++){
ans*=10;
ans+=a[i]-'0';
}
return ans;
}当然还有一种偷懒的办法,C++ 有个函数叫做 stoi(string),可以直接把字符串转成数字。
完整代码
#include<bits/stdc++.h>
using namespace std;
string a,b;
bool isd(string a){
for(char ch:a){
if(ch<'0'||ch>'9') return 0;
}
return 1;
}
int sti(string a){
int ans=0;
for(int i=0;i<a.size();i++){
ans*=10;
ans+=a[i]-'0';
}
return ans;
}
int main(){
cin>>a>>b;
if(isd(a)&&isd(b)) cout<<sti(a)-sti(b);
else cout<<"NaN";
return 0;
}