Register Operator Overloading

#include <cstdint>
#include <cstdio>

// Register abstraction
class Register32 {
private:
    std::uint32_t value;

public:
    // Constructor to initialize the register value
    explicit Register32(std::uint32_t initial_val) : value(initial_val) {}

    /**
     * Overload for the Bitwise OR assignment operator.
     * This allows: reg |= (1u << bit);
     */
    Register32& operator|=(std::uint32_t mask) {
        value |= mask;
        return *this;
    }

    /**
     * Overload for the Bitwise AND assignment operator.
     * This allows: reg &= ~(1u << bit);
     */
    Register32& operator&=(std::uint32_t mask) {
        value &= mask;
        return *this;
    }

    // Getter to retrieve the final raw value for printing
    std::uint32_t get() const {
        return value;
    }
};

int main() {
    Register32 reg{0};

    int n;
    if (std::scanf("%d", &n) != 1) return 0;

    for (int i = 0; i < n; ++i) {
        char op[6];
        int bit;
        std::scanf("%s %d", op, &bit);

        // These operations now call the overloaded operators defined above
        if (op[0] == 'S') {
            reg |= (1u << bit); 
        } else {
            reg &= ~(1u << bit);
        }
    }

    std::printf("reg=%u\n", reg.get());
    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

3 SET 0 SET 3 CLEAR 0

Expected Output

reg=8