My fast, easy to understand javascript solution - Non-recursive


  • 0
    S

    So the key thing is to find out the first three numbers

    var isAdditiveNumber = function(num) {
        var length = num.length;
        var numbers = [];
        for(var a = 1; a < length/2; a++){
            var n1 = num.substring(0, a);
            if((n1.charAt(0, 1) !== '0' && a > 1) || a === 1){
                var b = 1;
                var n2, n3;
                while(length - a - b >= a && length - a - b >= b){
                    n2 = num.substring(a, a + b);
                    if((n2.charAt(0) !== '0' && b > 1) || b === 1){
                        n3 = (parseInt(n2) + parseInt(n1)).toString();
                        if(num.substring(a + b, a + b + n3.length) === n3){
                            numbers = [parseInt(n1), parseInt(n2), parseInt(n3)];
                            if(checkrest(num, numbers)){
                                return true;
                            }
                        }                       
                    }
                    b++; 
                } 
            }
        }
        return false;
    };
    var checkrest = function(num, numbers){
        var i = 2;
        while((numbers[i] + numbers[i - 1]).toString() === num.substring(numbers.join('').length, numbers.join('').length + (numbers[i] + numbers[i - 1]).toString().length)){
            numbers.push(numbers[i] + numbers[i - 1]);
            i++;
        }   
        if(numbers.join('').length === num.length){
            return true;
        }else{
            return false;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.