【PAT甲级】Cut Integer
- 2019 年 11 月 8 日
- 筆記
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42449444/article/details/89449189
Problem Description:
Cutting an integer means to cut a K digits lone integer Z into two integers of (K/2) digits long integers A and B. For example, after cutting Z = 167334, we have A = 167 and B = 334. It is interesting to see that Z can be devided by the product of A and B, as 167334 / (167 × 334) = 3. Given an integer Z, you are supposed to test if it is such an integer.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 20). Then N lines follow, each gives an integer Z (10 ≤ Z <231). It is guaranteed that the number of digits of Z is an even number.
Output Specification:
For each case, print a single line Yes
if it is such a number, or No
if not.
Sample Input:
3 167334 2333 12345678
Sample Output:
Yes No No
解题思路:
输入string型的数字str,数字的位数为K(题目保证了K是偶数),然后通过stoi()函数把string型的数字str强制转换成int型的数字Z,通过substr()函数把数字str分成A和B,最后判断数字Z能否整除(数字A×数字B)即可。需要注意的是:除数不能为0!A×B不能为0,我第一次提交的时候就有俩个测试点出现了"Float Point Exception",浮点错误。
AC代码:
#include <bits/stdc++.h> using namespace std; int main() { int N; cin >> N; while(N--) { string str; cin >> str; int K = str.length(); //数字Z的位数,题目保证了K是偶数 int Z = stoi(str); //string型强制转换成int型 int A = stoi(str.substr(0,K/2)); //A是数字Z的前K/2位数字 int B = stoi(str.substr(K/2)); //B是数字Z的后K/2位数字 if((A*B != 0) && (Z%(A*B) == 0)) //当A*B=0时,编译器会报错"Float Point Exception",浮点错误 { cout << "Yes" << endl; } else { cout << "No" << endl; } } return 0; }