Dev-C++上就过不了
查看原帖
Dev-C++上就过不了
1213524
C_plus_plus_12345楼主2024/11/28 22:39
#include <iostream>
#include <vector>
#include <cmath>

// Helper function to count the number of carries in x + y (represented as strings)
int countCarries(const std::string& x_str, const std::string& y_str)
{
	int carry = 0;
	int count = 0;
	int maxLength = std::max(x_str.size(), y_str.size());

	// Pad the shorter string with leading zeros
	std::string x_padded = x_str, y_padded = y_str;
	if (x_str.size() < maxLength) x_padded = std::string(maxLength - x_str.size(), '0') + x_str;
	if (y_str.size() < maxLength) y_padded = std::string(maxLength - y_str.size(), '0') + y_str;

	// Calculate carries from right to left
	for (int i = maxLength - 1; i >= 0; --i)
	{
		int sum = (x_padded[i] - '0') + (y_padded[i] - '0') + carry;
		carry = sum / 10;
		if (carry > 0) ++count;
	}

	// Check if there's a carry-over from the most significant digit
	if (carry > 0) ++count;

	return count;
}

// Main function to find the appropriate y given x and k
std::string findY(int x, int k)
{
	std::string x_str = std::to_string(x);
	int maxLength = x_str.size();
	int maxPossibleY = pow(10, maxLength) - 1;

	for (int y = 0; y <= maxPossibleY; ++y)
	{
		std::string y_str = std::to_string(y);
		if (countCarries(x_str, y_str) == k)
		{
			return std::to_string(y);
		}
	}

	// If no such y is found, return an empty string or some indication
	return "-1"; // or you can throw an exception or return a specific value indicating failure
}

int main()
{
	int T;
	std::cin >> T;

	while (T--)
	{
		int x, k;
		std::cin >> x >> k;

		std::string result = findY(x, k);
		if (result != "-1")
		{
			std::cout << result << std::endl;
		}
		else
		{
			// Handle the case where no such y is found (optional, based on problem requirements)
			std::cout << "-1" << std::endl;
		}
	}

	return 0;
}
2024/11/28 22:39
加载中...