e545: 10019 - Funny Encryption Method

  1. 1. 內容
  2. 2. 範例輸入
  3. 3. 範例輸出
  4. 4. 想法
  5. 5. 程式碼

CPE 一顆星選集 49 道必考題

題目連結:https://zerojudge.tw/ShowProblem?problemid=e545

內容

給定一個十進制整數 N (0 < N <= 9999),分別計算將 N 當作十進位數值以及十六進位數值,轉換成二進位共有幾個 1 。

輸入第一列 T (0 < T <= 1000)代表測資數。

範例輸入

3
265
111
1234

範例輸出

3 5
6 3
5 5

想法

若是將 N 當成十進位看,直接轉二進位計算。若是當十六進位看,先將其轉為十進位,再轉二進位。

程式碼

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr)
using namespace std;

void dec(int);
void hex(int);
int main(){
fastio;
int T, N;
cin >> T;
while(T--){
cin >> N;
dec(N);
hex(N);
}
}
void dec(int n){
int c = 0;
while(n > 0){
if(n & 1) ++c;
n >>= 1;
}
cout << c << " ";
}
void hex(int n){
int c = 0, dig = 0, num = 0, temp;
while(n > 0){
num += (n % 10) * pow(16, dig);
n /= 10;
++dig;
}
while(num > 0){
if(num & 1) ++c;
num >>= 1;
}
cout << c << "\n";
}