PAT 1060. Are They Equal

一直没做出来,

参照点击打开链接的题解,重做了一遍才对。


先去除没用的先导0, 然后分 [0]+.[#]* 和 [0]*[#]+.[#]*这两种情况讨论。

注意到,在第一种情况里,最后的

		if (find_nonzero == false) // 不能省, 否则0.0会被记为*10^-1
		{
			exponent = 0;
		}

是不能略去的,否则不能测试点6 —— 考察0.0的输出是否为0.0 * 10 ^ 0



代码:

#include <string>
#include <iostream>
#include <sstream>

using namespace std;

int n;
string s1, s2, res1, res2;


string normlize(string& s1)
{
	string ret;
	int bits = 0, exponent = 0;

	size_t i;
	for (i = 0; i < s1.size() && s1[i] == '0'; ++ i) {}

	if (i < s1.size() && s1[i] == '.') // 0*.#*
	{
		bool find_nonzero = false;
		for (; i < s1.size(); ++ i)
		{
			if (s1[i] == '.')
			{
				exponent = 1; 
			} else if (s1[i] != '0')
			{
				find_nonzero = true;
			}
			if (find_nonzero == true)
			{
				if (bits < n)
				{
					ret.push_back(s1[i]);
					++ bits;
				}
			} else
			{
				-- exponent;	
			}
		}
		if (find_nonzero == false) // 不能省, 否则0.0会被记为*10^-1
		{
			exponent = 0;
		}
	} else  if (i < s1.size())     // 0*#*.#*
	{
		bool find_dot = false;
		for (; i < s1.size(); ++ i)
		{
			if (find_dot == false && s1[i] != '.')
			{
				++ exponent;
				if (bits < n)
				{
					ret.push_back( s1[i] );
					++ bits;
				}
			} else if (s1[i] == '.')
			{
				find_dot = true;
				continue;
			} else if (bits < n)
			{
				ret.push_back( s1[i] );
				++ bits;
			}				
		}
	}

	while (bits < n)
	{
		ret.push_back('0');
		++ bits;
	}
	ret = string("0.") + ret;
	ret += "*10^";
	stringstream ss;
	ss << exponent;
	string tmp;
	ss >> tmp;
	return ret + tmp;
}

int main()
{
	cin >> n >> s1 >> s2;

	res1 = normlize(s1);
	res2 = normlize(s2);

	if (res1 == res2)
	{
		cout << "YES " << res2 << endl;	
	} else
	{
		cout << "NO " << res1 << " " << res2 << endl;
	}

	system("pause");
	return 0;
}


你可能感兴趣的:(pat,科学计数法,有效位数,字符串模拟)