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

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, 2024 by avibootz
...