FastPrepCPU Register Bitwise Operations

CPU Register Bitwise Operations

Headlands Technologies logoHeadlands Technologies● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

Simulate one unsigned 32-bit register. You receive its initial nonnegative value initialValue and a sequence operations. Process the operations in order. Bit 0 is the least significant bit, and bit 31 is the most significant bit.

Each operation is a pair [opcode, bitIndex]:

  • 0: set that bit to 1.
  • 1: clear that bit to 0.
  • 2: toggle that bit.
  • 3: test that bit without changing the register.

Return one integer for every operation, in the same order. After set, clear or toggle, return the entire updated register value. For test, return 0 or 1 for the requested bit. Preserve repeated operations; an empty sequence returns an empty array.

Values from 0 through 4294967295 are nonnegative register values. Use signed 64-bit storage for the input and outputs so bit 31 is preserved without making the result negative.

Function

simulateRegister(initialValue: long, operations: int[][]) → long[]

Examples

Example 1

initialValue = 0operations = [[0,0],[0,3],[3,3],[1,0],[2,3],[3,3]]return = [1,9,1,8,0,0]

Set bits 0 and 3 to obtain 9. Testing bit 3 returns 1 without changing the register. Clearing bit 0 leaves 8; toggling bit 3 clears it.

Example 2

initialValue = 4294967295operations = [[3,31],[1,31],[3,31],[2,0],[0,31],[3,0]]return = [1,2147483647,0,2147483646,4294967294,0]

Bit 31 is a normal data bit. Clearing it leaves 2147483647. Later restoring it produces 4294967294, kept positive in signed 64-bit storage.

Example 3

initialValue = 10operations = [[3,0],[3,1],[2,0],[3,0],[0,1],[1,3],[3,3]]return = [0,1,11,1,11,3,0]

The initial value 10 has bits 1 and 3 set. Test returns a bit, toggle flips only the target, and setting an already-set bit leaves the value unchanged.

Constraints

  • 0 <= initialValue <= 4294967295.
  • 0 <= operations.length <= 100000.
  • Each operation contains exactly two integers: 0 <= opcode <= 3 and 0 <= bitIndex <= 31.
  • All operations are valid. No other CPU instructions or registers are simulated.

More Headlands Technologies problems

See Headlands Technologies hiring insights
public long[] simulateRegister(long initialValue, int[][] operations) {
    // write your code here
}
initialValue0
operations[[0,0],[0,3],[3,3],[1,0],[2,3],[3,3]]
expected[1,9,1,8,0,0]
Checking account…