2013年4月11日 星期四

10019 - Funny Encryption Method


The Problem

History : 
A student from ITESM Campus Monterrey plays with a new encryption method for numbers. These method consist of the following steps:Steps :  Example
1) Read the number N to encrypt M = 265
2) Interpret N as a decimal number X1= 265 (decimal)
3) Convert the decimal interpretation of N to its binary representation X1= 100001001 (binary)
4) Let b1 be equal to the number of 1’s in this binary representation B1= 3
5) Interpret N as a Hexadecimal number X2 = 265 (hexadecimal)
6) Convert the hexadecimal interpretation of N to its binary representation X2 = 1001100101
7) Let b2 be equal to the number of 1’s in the last binary representation B2 = 5
8) The encryption is the result of  M xor (b1*b2) M xor (3*5) = 262
This student failed Computational Organization, that’s why this student asked the judges of ITESM Campus Monterrey internal ACM programming Contest to ask for the numbers of 1’s bits of this two representations so that he can continue playing.
Task :
You have to write a program that read a Number and give as output the number b1 and b2

The Input

The first line will contain a number N which is the number of cases that you have to process. Each of the following N Lines ( 0<N<=1000) will contain the number M (0<M<=9999, in decimal representation)  which is the number the student wants to encrypt.

The Output

You will have to output N lines, each containing the number b1 and b2 in that order, separated by one space  corresponding to that lines number to crypt

Sample Input

3
265
111
1234

Sample Output

3 5 
6 3 
5 5


問題敘述

此題 input 的第一行會表示下面要輸入幾個整數,接著要將輸入的每個整數做兩件事情。第一: 先將它解讀成十進位並且轉換成二進位,輸出二進位中 1 的數量。第二: 將它解讀成十六進位並且轉換成二進位,輸出二進位中 1 的數量。輸出的兩個數字必須要用空白隔開。

解題思路

這題和 948 - Fibonaccimal Base (Chinese version) 一樣也是個進位轉換的題目,先將輸入的數字轉換成二進位,並且輸出二進位中 1 的數量。再將輸入的數字視為十六進位後先將它轉換成十進位再轉換成二進位,且輸出空白以及二進位中 1 的數量。

c++ 程式碼

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

int decToBin(int num, vector<int>& binTable) {
    int count = 0;

    for (int i=16; num; i--) {
        if (num >= binTable[i]) {
            num -= binTable[i];
            count++;
        }
    }
    return count;
}

int main() {
    int n;
    vector<int> binTable;
    vector<int> hexTable;
    int product = 1;

    for (int i=0; i<=16; i++) {
        binTable.push_back(product);
        product *= 2;
    }
    product = 1;
    for (int i=0; i<=3; i++) {
        hexTable.push_back(product);
        product *= 16;
    }
    cin >> n;
    for (int i=0; i<n; i++) {
        int num;
        int dec = 0;

        cin >> num;
        cout << decToBin(num, binTable);
        for (int j=0; num; j++) {
            dec += (num % 10) * hexTable[j];
            num /= 10;
        }
        cout << " " << decToBin(dec, binTable) << endl;
    }

    return 0;
}

沒有留言:

張貼留言