# UVA 10931 Parity ## 題目連結 [UVA 10931](https://vjudge.net/problem/UVA-10931) ### 題目內容 We define the parity of an integer n as the sum of the bits in binary representation computed modulo two. As an example, the number 21 = 101012 has three 1s in its binary representation so it has parity 3(mod2), or 1. In this problem you have to calculate the parity of an integer 1 ≤ I ≤ 2147483647. ### 輸入限制 Each line of the input has an integer I and the end of the input is indicated by a line where I = 0 that should not be processed. ### 輸出限制 For each integer I in the inputt you should print a line ‘The parity of B is P (mod 2).’, where B is the binary representation of I. ### 解題思路 這題要輸出二進制的數字,當temp除2的餘數等於0時push 0進字串中,反之則push 1進字串中,之後再將字串reverse就是二進制數字。 ### 程式碼 ```cpp= #include<bits/stdc++.h> using namespace std; int main(){ long long n; while(cin>>n && n!=0){ string a; long long cot=0; while(n!=0){ if(n%2==0){ a.push_back('0'); } else{ a.push_back('1'); cot++; } n/=2; } reverse(a.begin(),a.end()); cout<<"The parity of "<<a<<" is "<<cot<<" (mod 2)."<<endl; } } ``` ## 測資 ### Sample input 1 2 10 21 0 ### Sample output The parity of 1 is 1 (mod 2). The parity of 10 is 1 (mod 2). The parity of 1010 is 2 (mod 2). The parity of 10101 is 3 (mod 2). ## 中文題目連結 [zerojudge a132](https://zerojudge.tw/ShowProblem?problemid=a132)