Robert Eisele
Engineer, Systems Architect and DBA

Codingame: Numeral system

Original Problem

Goal

Your task is to identify minimal possible numeral system of the simple equality X+Y=Z.
Input
Line 1: A string S representing the equality X+Y=Z.
Output
Line 1 : Sought numeral system N.
Constraints
2 ≤ N ≤ 36
1 ≤ Length(X) ≤ 10
1 ≤ Length(Y) ≤ 10
1 ≤ Length(Z) ≤ 10

Solution

We can solve this problem by looping over all possible basis and convert the expression to a number in base \(b\) to check if the expression holds. As this problem lacks test cases, it's possible to use parseInt. The problem with this standard library function is that it tries to parse the beginning of a string as long as it's possible and not returns NaN. If you try to parse 2A in base 10, it returns 2, which could evaluate to a valid expression, even if it's false. That's why I implemented an own base converter:

function convert(str, base) {
    
  var L = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var s = 0;
  for (var i = 0; i < str.length; i++) {
    var c = L.indexOf(str[i]);
        
    if (c === -1 || c >= base) {
      return null;
    }
    s*= base;
    s+= c;
  }
  return s;
}

And we are ready to implement the expression check like this:

var terms = readline().split(/[+=]/);

for (var i = 2; i <= 36; i++) {
  var X = convert(terms[0], i);
  var Y = convert(terms[1], i);
  var Z = convert(terms[2], i);

  if (X !== null && Y !== null && Z !== null && X+Y===Z) {
    print(i);
    break;
  }
}

« Back to problem overview