How to check if a string contains only 0 and 1 and is divisible by 7 in C++

3 Answers

0 votes
#include <iostream>
#include <string>
#include <regex>

bool isBinary(const std::string& s) {
    static const std::regex binary("^[01]+$");
    
    return std::regex_match(s, binary);
}

/*
In decimal: reading "123" means
remainder = remainder * 10 + digit
 
In binary: reading "1011" means
remainder = remainder * 2 + bit
*/
 
/*
0   (0*2 + 0) % 7   0
0   (0*2 + 0) % 7   0
0   (0*2 + 0) % 7   0
1   (0*2 + 1) % 7   1
1   (1*2 + 1) % 7   3
1   (3*2 + 1) % 7   0
0   (0*2 + 0) % 7   0
0   (0*2 + 0) % 7   0
*/

bool divisibleBy7(const std::string& s) {
    int remainder = 0;

    for (char c : s) {
        remainder = (remainder * 2 + (c - '0')) % 7;
    }
    
    return remainder == 0;
}

int main() {
    std::string s = "00011100"; // 28

    if (!isBinary(s)) {
        std::cout << "Not a binary string\n";
        return 0;
    }

    if (divisibleBy7(s)) {
        std::cout << "Divisible by 7\n";
    } else {
        std::cout << "Not divisible by 7\n";
    }
}



/*
run:

Divisible by 7

*/

 



answered Feb 28 by avibootz
edited Mar 1 by avibootz
0 votes
#include <iostream>
#include <string>
#include <regex>

bool isBinaryAndDivisibleBy7(const std::string& s) {
    static const std::regex binary("^[01]+$");
    if (!std::regex_match(s, binary)) return false;

    int r = 0;
    for (char c : s) r = (r * 2 + (c - '0')) % 7;
    
    return r == 0;
}


int main() {
    std::string s = "00011100"; // 28

    if (isBinaryAndDivisibleBy7(s)) {
        std::cout << "Binary string and divisible by 7\n";
    } else {
        std::cout << "Not binary string or not divisible by 7\n";
    }
}



/*
run:

Binary string and divisible by 7

*/

 



answered Feb 28 by avibootz
0 votes
#include <iostream>
#include <string>
#include <algorithm>

bool is_binary(const std::string& s) {
    return !s.empty() &&
           std::all_of(s.begin(), s.end(),
                       [](char c) { return c == '0' || c == '1'; });
}

bool divisible_by_7(const std::string& s) {
    int r = 0;
    for (char c : s) {
        r = (r * 2 + (c - '0')) % 7;
    }
    
    return r == 0;
}

int main() {
    std::string s = "00011100"; // 28

    if (!is_binary(s)) {
        std::cout << "Not a binary string\n";
        return 0;
    }

    if (divisible_by_7(s)) {
        std::cout << "Divisible by 7\n";
    } else {
        std::cout << "Not divisible by 7\n";
    }
}



/*
run:

Divisible by 7

*/

 



answered Feb 28 by avibootz

Related questions

...