PAT 1069. The Black Hole of Numbers (stringstream)

可以用stringstream实现字符串和整型间的转换。


测试点5考察的是"Repeat in this manner we will soon end up at the number 6174 -- the "black hole" of 4-digit numbers."

我的理解是,输入若为6174, 则应输出 7641 - 1467 = 6174


#include <cstdio>
#include <algorithm>
#include <string>
#include <sstream>

using namespace std;

int n;

bool mycmp(const char a, const char b)
{
	return a > b;
}

bool same_numbers(int n)
{
	for (int i = 0; i < 10; ++ i)
	{
		if (n == 1111*i)
		{
			return true;
		}
	}
	return false;
}

void print_steps(int b)
{
	if (b == 6174)
	{
		printf("7641 - 1467 = 6174\n");
		return ;
	}

	string digit;
	stringstream ss;
	int a;
	while (b != 6174)
	{
		// get a
		digit.clear();
		ss.clear();
		ss << b;
		ss >> digit;
		while (digit.size() < 4)
		{
			digit.push_back('0');
		}
		sort(digit.begin(), digit.end());
		ss.clear();
		ss << digit;
		ss >> b;
		sort(digit.begin(), digit.end(), mycmp);
		ss.clear();
		ss << digit;
		ss >> a;
		printf("%04d - %04d = %04d\n", a, b, a-b);
		b = a - b;
	}
}

int main()
{
	scanf("%d", &n);

	if ( same_numbers(n) )
	{
		printf("%04d - %04d = 0000\n", n, n);
	} else
	{
		print_steps(n);
	}

	return 0;
}


你可能感兴趣的:(C++,pat,stringstream)