196k views
1 vote
Assigned newbits with the opposite values of oldbits if flipbits is true. ex: if oldbits = [1, 1, 0, 1] and flipbits is 1, then newbits = [0, 0, 1, 0]

User Peekmo
by
6.7k points

2 Answers

0 votes

Final answer:

To assign newbits with the opposite values of oldbits if flipbits is true, we can use the XOR operation to toggle the values.

Step-by-step explanation:

The question is asking us to assign newbits with the opposite values of oldbits if flipbits is true. In other words, if flipbits is 1, we need to change all the 1s in oldbits to 0s and all the 0s to 1s.

To solve this problem, we can iterate through each element in oldbits and use conditional statements to check if flipbits is true. If it is, we can use the XOR operation (^) to toggle the values. If flipbits is false, we can simply assign the same value.

Here is the step-by-step process:

Create an empty list called newbits.

Iterate through each element in oldbits.

Check if flipbits is true. If it is, use the XOR operation (^) to toggle the value. If not, assign the same value to newbits.

Store the new value in newbits.

Return newbits.

User Lahiru Pinto
by
6.3k points
2 votes

Franck's answer is better (using ~), but I just wanted to point out that the conditional in yours is slightly redundant. It's easy to forget that, since you already have a boolean value, you don't need to perform a comparison in your conditional. So you could have just done this...

if x x = false; else x = true; end
User Venkatesh Nannan
by
6.5k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.