HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Add one to a very large integer

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
onelargeveryintegeradd

Problem

I was asked to implement this in an interview a while back. I didn't pass the interview, mostly likely because it took me far too long to do. However, I'm interested to know how well implemented the actual code is.

The task was to:


Add one to a positive number represented as an array of integers.

The question is the same as this one. However, I have done it in JavaScript and my implementation is different (recursion rather than loops), so I hope they are sufficiently different.

var addToArray = function(n){
    var result = [];

    function carryOne(n) {
        if (n.length === 0) {
            result.push(1);
        }
        else {
            var length = n.length-1;
            if (n[length] < 9) {
                n[length] += 1;
                result.push(n);
            } else {
                result.push(0);
                carryOne(n.slice(0, length));
            }
        }
    }
    carryOne(n);
    result.reverse();
    var flatten = Array.prototype.concat.apply([], result);
    console.log(flatten);
}


I've just noticed I have missed the semicolons on the closing braces on the function definitions but I'm keeping it like that for honesty.

In general it works but I think the need to reverse and flatten the array at the end is quite inelegant, so I suspect there is a better solution.

Solution

The whole code is overengeneered, very much so in my opinion. The code can be reduced to:

function digitsIncrement(digits) {
    return toDigits(fromDigits(digits) + 1);
}


The two functions mentioned are easy to write, should take 1 to 5 lines each and be immediately understandable.

Remember to convert to a common format, calculate and convert back instead of working in a weird format.

Code Snippets

function digitsIncrement(digits) {
    return toDigits(fromDigits(digits) + 1);
}

Context

StackExchange Code Review Q#108056, answer score: 2

Revisions (0)

No revisions yet.