Computer >> Computer tutorials >  >> Programming >> Javascript

Determining whether numbers form additive sequence in JavaScript


Additive Numbers

Additive number is a number string whose digits can form additive sequence.

A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits '0'−'9', write a function to determine if it's an additive number.

Note − Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

For example −

The string "199100199" is additive number because, The additive sequence is − 1, 99, 100, 199 −

1 + 99 = 100, 99 + 100 = 199

Example

The code for this will be −

const str = "199100199";
const isAdditiveNumber = (numStr) => {
   if(numStr.length < 3) return false;
   let str = "";
   let seen = true;
   for(let i = numStr.length − 1; i > 1; i−−){
      str = `${numStr[i]}${str}`;
      if(numStr[i] === "0") continue;
      let s = str;
      let s2 = numStr[i − 1]
      for(let j = i − 2; j >= 0; j−−){
         if(`${s2}`.startsWith("0") && s2.length > 1){
            s2 = `${numStr[j]}${s2}` seen = false;
         } else if(parseInt(s) >= parseInt(s2)){
            let diff = s − s2;
            if(numStr.slice(0, j + 1).endsWith(diff)){
               s = s2;
               s2 = diff;
               let ind = Math.floor(Math.log10(diff));
               ind = ind < 0 ? 0 : ind
               j −= ind;
               seen = true;
            }else {
               s2 = `${numStr[j]}${s2}`
               seen = false;
            }
         }else{
            seen = false;
            break;
         }
      }
      if(seen) return seen;
   };
   return seen;
};
console.log(isAdditiveNumber(str));

Output

And the output in the console will be −

true