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 numb开发者_运维问答er 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.
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...
If I understand you correctly, you want a bit set in a result integer if and only if the corresponding bit is set in two or three input integers.
... so that's if the bit is set in the first number and the corresponding bit is set in either of the last two numbers or the corresponding bit is set in both of the last two numbers, so in a bitwise expression:
result = (a & (b | c)) | (b & c);
精彩评论