Monday, July 28, 2014

Quipu

Problem:

TopCoder Problem Statement - NAME

Overview:

Decode a rope with knots in it that represent an integer.

Java Source:
01: /*
02: TopCoder
03: Single Round Match: 155
04: Division: 2
05: Level: 1
06: Points: 250
07: Description: http://community.topcoder.com/stat?c=problem_statement&pm=1686
08:  */
09:
10: public class Quipu {
11:
12:     public int readKnots(String knots) {
13:
14:         int value = 0;
15:         int current = 0;
16:
17:         for (int i = 1; i < knots.length(); i++) {
18:
19:             if (knots.charAt(i) == 'X') {
20:                 current += 1;
21:
22:             } else {
23:                 value *= 10;
24:                 value += current;
25:                 current = 0;
26:             }
27:
28:         }
29:
30:         return value;
31:     }
32: }
Notes:

The problem may seem difficult at first, but the solution is actually very simple. value holds the number that we're going to eventually return. current holds the count at the current tens place. For each X that we encounter, increment current. When a space is encountered, multiply value by ten, add current, and then reset current back to zero. That's all there is to it.

Just one more thing. Notice that the for loop at line 17 starts at 1 instead of 0. This skips over the first '-'. Every String is guaranteed to start with a dash, so we just just skip over it.

No comments:

Post a Comment