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