Help me in solving BINPARITY problem

My issue

please help me out with this code. tell me what i am doing wrong

My code

#include <bits/stdc++.h>
using namespace std;

int main() {
	// your code goes here
	int t,n,count=0,rem;
	cin>>t;
	while(t--){
	    cin>>n;
	    while(n>=1){
	        rem=n%2;
	        count=count+rem;
	        n=n/2;
	    }
	    if(count%2==0){
	        cout<<"even"<<endl;
	    }
	    else{
	        cout<<"odd"<<endl;
	    }
	}

}

Problem Link: Binary Parity Practice Coding Problem - CodeChef

The problem is you are defining variables int t,n,count=0,rem; outside the test cases , so the sum is getting added for all the previous cases instead of starting from zero

1 Like

Correct Code is:

#include <iostream>
using namespace std;
int countSetBits(int n) {
    int count = 0;
    while (n) {
        count += n & 1;
        n >>= 1;
    }
    return count;
}
int main() {
    int T;
    cin >> T;
    for (int i = 0; i < T; ++i) {
        int N;
        cin >> N;
        int setBitsCount = countSetBits(N);
        if (setBitsCount % 2 == 0)
            cout << "EVEN" << endl;
        else
            cout << "ODD" << endl;
    }
    return 0;
}
2 Likes