天天看點

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;
}
           

繼續閱讀