PAT (Basic Level) Practise 1016 – 1020 解题报告

1016. 部分A+B (15)

解题思路: 就是给定两个数字以及分别给出一个个位整数, 从这两个数种抽出只含有这个个位整数的部分, 相加求和. 注意用long long 存结果以及计算, 貌似int存不下. 下面是AC代码:

#include <string>
#include <iostream>

long long extractPNumber(const std::string str, int d) {
	int len = str.size();
	long long itr = 1;
	long long res = 0;
	for(int i = 0; i < len; ++i) {
		if(str[i] - '0' == d) {
			res += d * itr;
			itr *= 10;
		}
	}
	return res;
}

int main() {
	std::string A, B;
	int Da, Db;

	std::cin >> A >> Da >> B >> Db;
	std::cout << extractPNumber(A, Da) + extractPNumber(B, Db) << std::endl;

	return 0;
}

1017. A除以B (20)

解题思路: 直接模拟草稿纸上的除法计算就行了. 注意几个特殊case, 比如求得的商的首位0输出问题, 4 / 8 应该输出 0, 4, 但是14/8 应该输出1, 6, 而不是01, 6. 下面是可以AC的代码:

#include <iostream>
#include <string>

int gao(const std::string & A, int B, std::string *pstrResult, int *pQuite) {
	int Q;
	int len = A.size();
	int curr = A[0] - '0';
	for(int i = 1; i < len; ++i) {
		Q = curr % B;
		pstrResult->push_back(curr / B + '0');
		curr = Q * 10 + A[i] - '0';
	}
	Q = curr % B;
	pstrResult->push_back(curr / B + '0');

	*pQuite = Q;
	return 0;
}

int main() {
	std::string A;
	int B;
	std::cin >> A >> B;

	std::string strResult;
	int iQuote;

	int iRet = gao(A, B, &strResult, &iQuote);
	if(iRet) {
	}

	if(strResult.size() > 1 && strResult[0] == '0')
		std::cout << strResult.substr(1) << ' ' << iQuote << std::endl;
	else
		std::cout << strResult << ' ' << iQuote << std::endl;
	return 0;
}

1018. 锤子剪刀布 (20)

解题思路: 直接模拟解决, 可能是想考察编程的基本功吧. 按照字典序, B-C-j来做的话, 代码可以更加精简一点. 下面是可以AC的代码:

#include <iostream>
#include <algorithm>

int comp(char a, char b) {
	if(a == b) return 0;
	if( ('C' == a && 'J' == b) ||
		('J' == a && 'B' == b) ||
		('B' == a && 'C' == b)
		)
		return 1;
	return -1;
}

int mapping(char c) {
	if('B' == c) return 0;
	if('C' == c) return 1;
	return 2; // 'J'
}

char maxChar(int chArray[3]) {
	int maxV = *std::max_element(chArray, chArray + 3);
	if(chArray[0] == maxV)
		return 'B';
	if(chArray[1] == maxV)
		return 'C';
	return 'J';
}

int main() {
	int n;
	std::cin >> n;
	char a, b;
	int iCountWin = 0;
	int iCoundEven = 0;
	int cnt1[3] = {0, 0, 0};
	int cnt2[3] = {0, 0, 0};

	for(int i = 0; i < n; ++i) {
		std::cin >> a >> b;
		int ret = comp(a, b);
		if(1 == ret) {
			++iCountWin;
			++cnt1[mapping(a)];
		}
		else if(0 == ret)
			++iCoundEven;
		else {
			++cnt2[mapping(b)];
		}
	}
	std::cout << iCountWin << ' ' << iCoundEven << ' ' << n - iCoundEven - iCountWin << std::endl;
	std::cout << n - iCoundEven - iCountWin << ' ' << iCoundEven << ' ' << iCountWin << std::endl;
	std::cout << maxChar(cnt1) << ' ' << maxChar(cnt2) << std::endl;
	return 0;
}

1019. 数字黑洞 (20)

解题思路: 同”PAT 解题报告 1069. The Black Hole of Numbers (20)

1020. 月饼 (25)

解题思路: 同”PAT 解题报告 1070. Mooncake (25)

 

(全文完,原创文章,转载时请注明作者和出处)


(转载本站文章请注明作者和出处 烟客旅人 sigmainfy — http://www.sigmainfy.com,请勿用于任何商业用途)

Written on December 25, 2013