Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,037 questions

40,821 answers

573 users

How to remove characters from a numeric string such that the string becomes divisible by 8 in JavaScript

1 Answer

0 votes
function checkIfNumExist(num, s) {
    let index = 0;
    
    for (let ch of s) {
        if (num[index] === ch) {
            index++;
            if (num.length === index) {
                break;
            }
        }
    }
    
    return index === num.length ? 1 : 0;
}

function convertStringToBecomesDivisibleBy8(s) {
    for (let i = 8; i < 1e3; i += 8) {
        let num = i.toString();
        if (checkIfNumExist(num, s) === 1) {
            return num;
        }
    }
    
    return "-1";
}

let s1 = "127892";
let result = convertStringToBecomesDivisibleBy8(s1);
console.log(result);

let s2 = "1201674";
result = convertStringToBecomesDivisibleBy8(s2);
console.log(result);

let s3 = "1209574";
result = convertStringToBecomesDivisibleBy8(s3);
console.log(result);

let s4 = "190395473";
result = convertStringToBecomesDivisibleBy8(s4);
console.log(result);

let s5 = "1309577";
result = convertStringToBecomesDivisibleBy8(s5);
if (result !== "-1") {
    s5 = result;
    console.log(s5);
} else {
    console.log("No numeric characters combination divisible by 8");
}



/*
run:

8
16
24
104
No numeric characters combination divisible by 8

*/

 





answered Mar 19 by avibootz
...