DEV Community

Cover image for Amal’s First Switch Equation: Clean FizzBuzz with Bitmask Logic
Amal p
Amal p

Posted on

Amal’s First Switch Equation: Clean FizzBuzz with Bitmask Logic

Amal’s First Switch Equation: Clean FizzBuzz with Bitmask Logic 🧠

Most FizzBuzz solutions rely on if...else... chains. But what if you were challenged to use only a switch statement? That’s exactly what led me (Amal from Kerala) to discover something elegant — an equation that combines multiple boolean checks into a single integer key using powers of two.


💡 The Equation

For n conditions, define:

Key = (result % x1== 0)*2⁰ + (result % x2 == x2)*2¹+………+(result % xn== 0)*2^n-1

🧩 FizzBuzz Example

int i = 1, result, key;
    while(i <= limit) {
        result = i * num;
        key = (result % 3 == 0) * 1 + (result % 5 == 0) * 2;

        switch(key){
            case 1:
                printf("%d x %d = %s\n", num, i, "PIZZ");
                break;
            case 2:
                printf("%d x %d = %s\n", num, i, "BUZZ");
                break;
            case 3:
                printf("%d x %d = %s\n", num, i, "PIZZBUZZ");
                break;
            case 0:
            default:
                printf("%d x %d = %d\n", num, i, result);
        }

        i++;
    }
Enter fullscreen mode Exit fullscreen mode

🎯 Why It Works

  • Each boolean becomes a unique bit in a binary key.
  • Combinations are naturally mapped to cases.
  • You get scalable, clean switch statements.
  • Great for teaching logic, bitmasking, and scalable code patterns.

🌱 My Discovery Journey

I didn’t find this formula in any book or tutorial — it came from a challenge in a session where “no if-else, only switch!” was the rule. Through experimentation and abstraction, I ended up with this reusable bitmask method.

💬 Join the Conversation

Would love your feedback!

🔍 What other scenarios could use bitmask-based switches?

🔍 Have you seen this in other languages or problems?
Enter fullscreen mode Exit fullscreen mode

🔗 Check out the full code & story here: [https://gist.github.com/amalpvatayam67/0f6d3fbc9f72dd5a978513008e6a50dd]

Happy coding! 😊
— Amal, Cybersecurity Enthusiast from Kerala

Top comments (1)

Collapse
 
pauljlucas profile image
Paul J. Lucas

There's no bit-masking going on here. Unless you're using either the & or | operators, you're not doing bit-masking. If you want actual bit-masking:

key = (result % 3 == 0) | ((result % 5 == 0) << 1);
Enter fullscreen mode Exit fullscreen mode

It would also be cleaner if:

enum FB {
    FIZZ     = 1 << 0,
    BUZZ     = 1 << 1,
    FIZZBUZZ = FIZZ | BUZZ
};
Enter fullscreen mode Exit fullscreen mode

then:

enum FB key = (enum FB)((result % 3 == 0) | ((result % 5 == 0) << 1))'

switch ( key ) {
    case FIZZ:
        // ...
    case BUZZ:
        // ...
    case FIZZBUZZ:
        // ...
}
Enter fullscreen mode Exit fullscreen mode