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

1 Answer

0 votes
using System;
using System.Text.RegularExpressions;

class BinaryDivisibleBy7
{
    // Check if a string contains only '0' and '1'
    static bool IsBinary(string s) {
        // Compiled once and reused
        Regex binary = new Regex("^[01]+$");
        
        return binary.IsMatch(s);
    }

    /*
    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
    */

    // Compute binary string modulo 7 without overflow
    static bool DivisibleBy7(string s) {
        int remainder = 0;

        foreach (char c in s) {
            remainder = (remainder * 2 + (c - '0')) % 7;
        }

        return remainder == 0;
    }

    static void Main()
    {
        string s = "00011100"; // 28

        if (!IsBinary(s)) {
            Console.WriteLine("Not a binary string");
            return;
        }

        if (DivisibleBy7(s)) {
            Console.WriteLine("Divisible by 7");
        }
        else {
            Console.WriteLine("Not divisible by 7");
        }
    }
}



/*
run:

Divisible by 7

*/

 



answered Mar 1 by avibootz
edited Mar 1 by avibootz

Related questions

...