Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C Bitwise Operators in a Referendum - Homework

I'm doing a C homework project and I'm incredibly lost. Essentially, I have to make function called majority that takes in 3 short integers, and spits out another number based on the inputs. I'll give an example from the project:

Basically, I make the function majority(101010101010101, 101010101010101, 101010101010101), and if there are 2 or more 1's in that bit, return 1, else return 0.

Thus far, I have

short majority(short a, short b, short c)
{
    return (a | b | c);
}

Now, I know that this isn't right at all, so I'm asking here: How would I go about doing this? Thank you for the help, and I apologize if this is kinda hard to follow. I can edit as necessary.

like image 837
Z. Charles Dziura Avatar asked Jan 29 '26 17:01

Z. Charles Dziura


1 Answers

There's more than one way of doing this, but one possibility is:

short majority(short a, short b, short c)
{
    return (a & b) | (b & c) | (c & a);
}

As this is homework I'll let you work for yourself out how/why this works, and see if you can come up with an alternate, perhaps even better solution...

like image 102
Paul R Avatar answered Jan 31 '26 08:01

Paul R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!