HDU_2054 A == B ?(字符串处理)

A == B ?

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 154525    Accepted Submission(s): 25065

Problem Description
Give you two numbers A and B, if A is equal to B, you should print "YES", or print "NO".
 
Input
each test case contains two numbers A and B.
 
Output
for each case, if A is equal to B, you should print "YES", or print "NO".
 
Sample Input
1 2 
2 2 
3 3 
4 3
Sample Output
NO 
YES 
YES 
NO

题目看似简单其实有很多奇形怪状的数据,看了Discuss里面最新的题解觉得思路很流畅,想记录一下,对于以后处理数字型字符串有点帮助。

步骤:

  1. 去符号
  2. 去前导零
  3. 有小数点的话把后面多余的零也去掉
  4. 如果最后一位是小数点就删掉
#include <iostream>
#include <string>
using namespace std;
char getValid(string &s){
    char st = '+';
    //保存符号 然后删掉
    if(s[0]=='+'||s[0]=='-'){
        st = s[0];
        s.erase(s.begin());
    }
    //删除前导零
    while(s.size()!=0&&s[0]=='0'){
        s.erase(s.begin());
    }
    //有小数点 删除后续零
    if(s.find('.')!=string::npos){
        while(s.size()!=0&&s[s.length()-1]=='0'){
            s.erase(s.end()-1);
        }
    }
    //删除最后的小数点
    if(s[s.length()-1]=='.'){
        s.erase(s.end()-1);
    }
    return st;
}
int main(){
    string a,b;
    while(cin>>a>>b){
        char aop = getValid(a);
        char bop = getValid(b);
        //正负零无论怎么样都相同
        if(a.size()==0&&b.size()==0)cout<<"YES"<<endl;
        else if(aop==bop&&a==b)cout<<"YES"<<endl;
        else cout<<"NO"<<endl;
    }
    return 0;
}
发布了38 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40167974/article/details/104329088