Andre - 2 months ago 216

C++ Question

`The decimal zip of two non-negative integers A and B is an integer C whose`

decimal representation is created from the decimal representations

of A and B as follows:

• the first (i.e. the most significant) digit of C is the first digit of A;

• the second digit of C is the first digit of B;

• the third digit of C is the second digit of A;

• the fourth digit of C is the second digit of B;

• etc.

If one of the integers A and B runs out of digits, the remaining digits of

the other integer are appended to the result.

The decimal representation of 0 is assumed to be "0".

For example, the decimal zip of 12 and 56 is 1526.

The decimal zip of 56 and 12 is 5162.

The decimal zip of 12345 and 678 is 16273845.

The decimal zip of 123 and 67890 is 16273890.

Write a function: function solution(A, B); that, given two non-negative

integers A and B, returns their decimal zip.

The function should return -1 if the result exceeds 100,000,000.

For example, given A = 12345 and B = 678 the function should return

16273845, as explained above.

Assume that:

• A and B are integers within the range [0..100,000,000].

here is my solution, but I get an array bound expection

so I tried to convert the integer to string so that I process it, and add the digits together.

`int solution(int A, int B) {`

// write your code in C++11 (g++ 4.8.2)

if (A < 0 || A > 100000000) return -1;

if (B < 0 || B > 100000000) return -1;

string A_ = IntToString(A);

string B_ = IntToString(B);

string output = "";

for (int i = 0; i < A_.size() || i < B_.size(); i++) {

if (A_[i]) {

output[i] = output[i] + A_[i];

}

if (B_[i]) {

output[i] = output[i] + B_[i];

}

}

return atoi(output.c_str());

}

Answer

You `for`

loops only stops when `i`

reaches the size of the *largest* string. But you continue to use `i`

as an index into *both* strings. So you'll exceed the bounds of the shorter one, causing an error.

Instead of:

```
if (A_[i])
```

You probably want:

```
if (i < A_.size())
```