a753簡單同字串的十進位與十六進位位元數
CPE:Funny Encryption Method (UVa 10019)
區分表示文字與其在不同基底下的數值。
解題思路
同一字串例如 265,十進位值是 265,十六進位值則是 2×16²+6×16+5=613。第一個答案計算十進位值的二進位 1 數量,反覆取最低位並右移即可。
第二個答案也可逐字算,因為每個十六進位數字恰好對應四個互不重疊的位元,所以各十進位數字 0 到 9 的 1 數量相加即可。這樣不必真的產生二進位字串。讀測試筆數後,每題輸出 b1 b2,中間一個空白。
Step-by-step animation
示意:字串 12
步驟 1 / 3
十進位解讀
12 的二進位為 1100,共兩個 1。
1
1
0
0
- b1
- 2
#include <iostream>
#include <string>
using namespace std;
int bits(int x) {
int ans = 0;
while (x) {
ans += x & 1;
x >>= 1;
}
return ans;
}
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
int b2 = 0;
for (char c : s)
b2 += bits(c - '0');
cout << bits(stoi(s)) << ' ' << b2 << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。