Question

I recently had to do a codility test. The question itself was reasonably easy. take a string of numbers and +, * loop through it, if the character is a number, add it to a stack, if its an operation pop two items off the stack, perform the operation and put the result back on the stack.

The tricky small print however, specifed that the stack store values as 12 bit unsigned ints.

This gave me a lot of trouble I tried bitwise shifting back and forth but got negative numbers and eventualy I had to just do % 4096 before I ran out of time.

Also I realised that really I might have to create a special 12bit add and multiply operators, or would I be ok just converting a 16bit result?

Have I missed a trick?

What is the best way to emulate 12 bit uint math in c#?

Was it helpful?

Solution

A simple operation like

  PushToStack(uint32 value)
  {
     _stack.Add(value % 4096);
  }

should be sufficient, as long as you use this function exclusively for pushing values to your stack.

Note that (a+b)%n == (a%n + b%n)%n and (a*b)%n == ((a%n) * (b%n))%n for a and b >=0 and n>0.

Furthermore, when you add or multiply two values from the stack, the input values are already 12 bit, so the output has at maximum 24 bit, so you can do this using unsigned or signed 32bit arithmetics without getting an overflow. Thus there will be never any negative value occur, and any kind of bit shifting is unnecessary. And as soon as the result is pushed to the stack again, it becomes 12 bits again.

Licensed under: CC-BY-SA with attribution
scroll top