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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,988 questions

51,933 answers

573 users

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

1 Answer

0 votes
#include <iostream>

int checkIfNumExist(std::string num, std::string s) {
    int index = 0;
   
    for (char ch : s) {
        if (num[index] == ch) {
            index++;
            if ((int)num.size() == index ) {
                break;
            }
        }
    }
   
   return index == (int)num.size();
}

std::string convert_string_to_becomes_divisible_by_8(std::string s) {
    for (int i = 8; i < 1e3; i += 8) {
        std::string num = std::to_string(i);
        if (checkIfNumExist(num, s)) {
            return num;
        }
    }
    
    return "-1";
}

int main() {
    std::string s1 = "127892";
    std::string result = convert_string_to_becomes_divisible_by_8(s1);
    std::cout << result << "\n";
   
    std::string s2 = "1201674";
    result = convert_string_to_becomes_divisible_by_8(s2);
    std::cout << result << "\n";
    
    std::string s3 = "1209574";
    result = convert_string_to_becomes_divisible_by_8(s3);
    std::cout << result << "\n";
    
    std::string s4 = "190395473";
    result = convert_string_to_becomes_divisible_by_8(s4);
    std::cout << result << "\n";
    
    std::string s5 = "1309577";
    result = convert_string_to_becomes_divisible_by_8(s5);
    if (result != "-1") {
        s5 = result;
        std::cout << s5 << "\n";
    } else {
        std::cout << "No numeric characters combination divisible by 8" << "\n";
    }
}



/*
run:

8
16
24
104
No numeric characters combination divisible by 8

*/

 



answered Mar 19, 2024 by avibootz
edited Mar 19, 2024 by avibootz
...