Monday, August 6, 2018

Codeforces 282A Bit++ Solution in C (Explained)

Bit++ (282A) describes a tiny programming language with one variable and two operations. Simulating it is straightforward. The nice part is noticing that you do not need to compare whole strings at all: one character tells you everything.

The problem in short

The language has a single variable x, which starts at 0, and two operations: ++ adds 1 and -- subtracts 1. Each statement is exactly three characters: the operation and the variable, in either order, so it is one of X++, ++X, X-- or --X. Given n statements (1 ≤ n ≤ 150), print the final value of x.

Full statement: Codeforces 282A – Bit++.

Key observation

Look at the four possible statements with their characters numbered from 0:

X++   ++X   X--   --X
 ^     ^     ^     ^
index 1 is always '+' or '-'

Whatever the order, the middle character (index 1) is always part of the operation. So the whole statement can be decided by checking stmt[1]: if it is '+', increment, otherwise decrement.

The original version of this post compared each statement against all four strings using strcmp. That is correct too, but it is longer and gives you four chances to make a typo.

Example

2
X++
--X

The first statement has '+' in the middle, so x becomes 1. The second has '-', so x goes back to 0.

Solution in C

#include <stdio.h>

int main(void) {
    int n, x = 0;
    char stmt[4];
    scanf("%d", &n);

    while (n--) {
        scanf("%s", stmt);
        /* The middle character is always '+' or '-',
           whether the statement is X++, ++X, X-- or --X. */
        if (stmt[1] == '+')
            x++;
        else
            x--;
    }

    printf("%d\n", x);
    return 0;
}

The buffer is 4 characters: 3 for the statement plus 1 for the terminating '\0'. Making it size 3 is a classic buffer overflow.

Complexity

O(n) time, O(1) extra memory.

What to take away

Before writing a comparison for every possible input, look for a position or property that all cases share. It makes code shorter and harder to get wrong. You will see the same trick in 339A Helpful Maths, where digits always sit at even positions in the input.

No comments:

Post a Comment