UVa10931 Parity
Last updated on a year ago
- ❗️ 題意
 給定數字n,請求出n這個數字的二進位為何與它的二進位數字有幾個1
- ✔️ 題解
 我們可以直接利用模擬的方式,每次就是先看這個數字除以2的餘數為何,之後再除以2就好,在過程中當餘數為1時可以紀錄下來,就是二進位數字中共有多少一。
- 💻 程式碼10ms 也可以利用python的bin來簡化程式碼1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22#include <bits/stdc++.h>
 using namespace std;
 int main(){
 int num;
 while(cin >> num && num != 0){
 string st;
 int cnt = 0;
 while(num != 0){
 if(num % 2 == 0){
 st += '0';
 }
 else{
 cnt++;
 st +='1';
 }
 num /= 2;
 }
 reverse(st.begin(), st.end());
 cout << "The parity of " << st << " is " << cnt << " (mod 2).\n";
 }
 }10ms 1 
 2
 3
 4
 5while True:
 num = int(input())
 if num == 0:
 break
 print(f'The parity of {str(bin(num))[2:]} is {str(bin(num)).count("1")} (mod 2).')
- 🧠 心得
 自從開始做畢業專題後寫python的時間比寫c++的時間多太多了,程式語言就是個工具,不同場合需要使用的語言本來就不同,對我來說c++多半是拿來解題較多,而其他時間多是使用python。
UVa10931 Parity
      http://example.com/2022/08/30/20220830/