Hamiltonian Hypercube

Given two binary strings in Gray Code order, count how many code words lie strictly between them on the n-bit Gray Code path.

Medium6Bit manipulationRecursionDivide and conquerInterviewNo attempts yetTime limit2sMemory limit512 MB

Problem

Hypercube graphs are very regular, and you have spent a lot of time on the mathematics around them. The vertices of a hypercube graph of dimension nn are all binary strings of length nn, and two vertices are connected when they differ in exactly one position. Hypercube graphs are related to error-correcting codes in several ways.

One of those relationships involves the nn-bit Gray Code, an ordering of the binary strings of length nn defined recursively. The words of the nn-bit code start with the words of the (n1)(n-1)-bit code, each with a 0 prepended, followed by the same words in reverse order, each with a 1 prepended. The 1-bit Gray Code consists of 0 and 1. For example, the 3-bit Gray Code is this sequence:

000, 001, 011, 010, 110, 111, 101, 100

The nn-bit Gray Code forms a Hamiltonian path in the nn-dimensional hypercube, a path that visits every vertex exactly once (see Figure 1).

Figure 1: the 3-dimensional hypercube and the Hamiltonian path that corresponds to the 3-bit Gray Code.

You wonder how many vertices lie between the vertices 0n0^n (nn zeros) and 1n1^n (nn ones) on that path. The count is at least 2n112^{n-1}-1 and at most 2n22^n-2, because 0n0^n is always the first vertex and 1n1^n sits somewhere in the second half of the path. Once you have answered that question, you want to generalise it and write a program that determines the number of vertices between two arbitrary vertices of the hypercube on the path given by the Gray Code.

Input

The input is a single line containing:

  • one integer nn (1n601 \le n \le 60), the dimension of the hypercube
  • two binary strings aa and bb, both of length nn, where aa comes before bb in the nn-bit Gray Code

Output

Print the number of code words between aa and bb in the nn-bit Gray Code.