PAT-1132 Cut Integer (整数分割)

Cutting an integer means to cut a K digits long 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 x 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



题目大意:将一个k位(k为偶数)的整数拆成两半(即前k/2位 和 后k/2位),要求判断原数是否能整除于这两个数的积。


主要思路:很简单的题目,只需要写一个计算整数位数的函数,将整数不断除以10,直到该数变为0即可累积得到该数的位数k。将该数除以10^(k/2)可得到前半部分,而求余则可以得到后半部分,最后用原数对两部分的积求模即可完成判断。需要注意的是,如果两部分的乘积为0则会使除数为0,出现浮点错误,也就是说在取模之前需要判断后半部分数是否为0,如果为0则直接输出No。

#include <iostream>
#include <cmath>
using namespace std;

//计算整数的位数
int count_bit(int x) {
    int count = 0;
    while (x > 0) {
        x /= 10;
        count++;
    }
    return count;
}

int main(void) {
    int n, z, i;
    
    cin >> n;
    for (i = 0; i < n; i++) {
        cin >> z;
        int mid = count_bit(z) / 2;
        int t = pow(10, mid);
		// z % t == 0 会产生浮点错误,比如当 z = 1000 时
        if (z % t > 0 && z % ((z % t) * (z / t)) == 0)		
            cout << "Yes" << endl;
		else
			cout << "No" << endl;
    }  
    
    return 0;
}

posted @ 2017-09-17 20:50  zhayujie  阅读(135)  评论(0编辑  收藏  举报