JavaScript
// ------------------------------------------
// TIME TAKEN: 20 MINUTES
// ------------------------------------------
function addOne(arr, base) {
if (! base) {
base = 10;
}
let carry;
let pos = arr.length - 1;
while (pos >= 0) {
carry = false;
if (canPositiveOverflow(arr[pos], base)) {
arr[pos] = 0;
carry = true;
} else if (canNegativeOverflow(arr, pos)) {
arr[pos] = (base - 1) * (-1);
carry = true;
} else {
arr[pos] += 1;
}
if (! carry) {
break;
}
pos--;
}
if (carry) {
arr.unshift(1);
}
if (arr[0] == 0) {
arr.shift();
}
return arr;
}
function canPositiveOverflow(value, base) {
return value == base - 1;
}
function canNegativeOverflow(arr, pos) {
if (arr[0] < 0) {
return arr[pos] == 0;
}
return false;
}
// --------------------------------------------
// TESTS BELOW - PLEASE ADD YOUR OWN TEST CASES
// --------------------------------------------
expect('addOne([5, 1, 2])', addOne([5, 1, 2]), [5, 1, 3]);
expect('addOne([0])', addOne([0]), [1]);
expect('addOne([9, 9])', addOne([9, 9]), [1, 0, 0]);
expect('addOne([1, 9, 9])', addOne([1, 9, 9]), [2, 0, 0]);
expect('addOne([-3, -7])', addOne([-3, -7]), [-3, -6]);
expect('addOne([-1, 0, 0])', addOne([-1, 0, 0]), [-9, -9]);
expect('addOne([1, 0, 1], 2)', addOne([1, 0, 1], 2), [1, 1, 0]);
expect('addOne([1, 1, 1], 2)', addOne([1, 1, 1], 2), [1, 0, 0, 0]);
// ------------------------------------------
function compareArrays(arr1, arr2) {
return $(arr1).not(arr2).length == 0 && $(arr2).not(arr1).length == 0;
}
function expect(name, a, b) {
if (a !== b && !(a instanceof Array && b instanceof Array && compareArrays(a, b))) {
$('ul').append('<li class="error">Testing <code>' + name + '</code> ...<br />Error: <code>' + a + '</code> is the wrong answer</li>');
} else {
$('ul').append('<li class="success">Testing <code>' + name + '</code> ...<br>Right: <code>' + a + '</code> is the...