HDU 2054 A==B?题解

A == B ?

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


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

题目意思很简单,就是比较A与B是否相等,但是题目中没有给条件限制,如果单纯只考虑整型的数据提交就会WA!由于不知道输入的数据是什么类型的,所以需要先用字符串对数据进行存储,然后在考虑数据的特殊情况。

本题需要考虑的特殊情况有以下几种:

1.一个数有很多前置0;

2.小数有很多后置无用0;

3.一个数的最后一位有小数点但是没有小数部分。

    对于这些情况,需要将字符串进行删减,或者用变量标记字符串中有用的部分,我选择的是对字符串进行删减。

    删去不需要的部分,用char类型的话也可以,但是需要将很多string类中已有的函数自己再重新写一遍,所以我用的是string类。并且直接用string类中的函数。

    string类中strchr(char *a,char c)函数是查找字符串中第一个出现字符c的地方,而string.c_str()是将string里的一个字符转换成char *类型。

    string类中的erase(int a,int b)函数是删除字符串中从a到b之间的字符,可以将字符串缩减,便于比较。

#include <iostream>
#include <string>
using namespace std;
void change(string &a)
{
	int len = a.length();
	if (strchr(a.c_str(), '.'))//在字符串中查找是否有小数点
	{
		while (a[--len] == '0')
			a.erase(len, 1);
		if (a[len] == '.')
			a.erase(len, 1);
	}
	while (a[0] == '0')//解决一个数中有很多前置0的问题
		a.erase(0, 1);
}
int main()
{
	string a, b;
	while (cin >> a >> b)
	{
		change(a);
		change(b);
		if(a.compare(b))
			cout << "NO" << endl;
		else
			cout << "YES" << endl;
	}
	return  0;
}
关于string类中的strchr函数和strcchr函数的详解可参看: strchr()函数与strrchr()函数的实现



猜你喜欢

转载自blog.csdn.net/weixin_39924920/article/details/79723341