uva 10931 - Parity

本文介绍了一个简单的算法,用于计算任意给定整数(范围1至2^31-1)的二进制表示中1的个数的奇偶性,并通过示例输入输出展示了如何使用该算法。

 Parity

Time Limit: 1 second

We define the parity of an integer n as the sum of the bits in binary representationcomputed modulo two. As an example, the number 21 = 101012 has three 1sin its binary representation so it has parity 3 (mod 2), or 1.

In this problem you have to calculate the parity of an integer 1 ≤ I ≤ 2147483647.

Input

Each line of the input has an integer I and the end of the input is indicated by a linewhere I = 0 that should not be processed.

Output

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.

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).


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include <queue>

using namespace std;
#define maxn 10005
#define inf 0x7ffffff
pair <int ,int > p;
int arr[maxn];
int n;
//int cmpD(Node a,Node b){
//    return a.h > b.h;
//}
//int cmpI(Node a,Node b){
//    return a.h < b.h;
//}
int main()
{
    while(scanf("%d",&n) != EOF && n){
        int tmp = n;
        int cnt = 0;
        int ans = 0;
        while(tmp){
            arr[cnt] = tmp % 2;
            if(arr[cnt] == 1){
                ans ++;
            }
            tmp /= 2;
            cnt++;
        }
        printf("The parity of ");
        for(int i = cnt - 1; i >= 0; i--){
            printf("%d",arr[i]);
        }
        printf(" is %d (mod 2).\n",ans);
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值