Why isn't an (intentional) overflow occuring in my python FizzBuzz implementation?

55 Views Asked by At

I noticed that two out of three of the values generally associated with FizzBuzz are one less than a value of 2n, and that made me want to try an implementation where it uses overflows instead of resetting the counters to zero manually. I've never really messed with individual bits before, so this is very new to me.

I tried writing the following code in python:

def fizzBuzz(n):
    fizz = 0b00  # 2-bit counter
    buzz = 0b000  # 3-bit counter
    fizzbuzz = 0b0000  # 4-bit counter
    for i in range(1, n + 1):
        fizz += 0b01  # Increment fizz counter
        buzz += 0b001  # Increment buzz counter
        fizzbuzz += 0b0001  # Increment fizzbuzz counter

        if fizzbuzz == 0b1111:  # Check for 15 in 3-bit counter
            yield "FizzBuzz"
        elif fizz == 0b11:  # Check for 3 in 2-bit counter
            yield "Fizz"
        elif buzz == 0b101:  # Check for 5 in 3-bit counter
            yield "Buzz"
            buzz = 0b000  # Reset buzz counter because it is not a multiple of 2^n-1.
        else:
            yield str(i)


print(list(fizzBuzz(20)))


The expected outcome would be (obviously):

['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz', '16', '17', 'Fizz', '19', 'Buzz']

But instead it is returning:

['1', '2', 'Fizz', '4', 'Buzz', '6', '7', '8', '9', 'Buzz', '11', '12', '13', '14', 'FizzBuzz', '16', '17', '18', '19', '20']

Notice that it stops working after the first Fizz when it should just overflow to 0b00 again and start counting up? Even if the counting is wrong, I should at least see more than one Fizz.

0

There are 0 best solutions below