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

1 Answer

0 votes
import java.util.regex.Pattern;

public class BinaryDivisibleBy7 {

    // Check if a string contains only '0' and '1'
    static boolean isBinary(String s) {
        // Java compiles regex patterns once when declared static final
        final Pattern binary = Pattern.compile("^[01]+$");
        
        return binary.matcher(s).matches();
    }

    // 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 boolean divisibleBy7(String s) {
        int remainder = 0;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            remainder = (remainder * 2 + (c - '0')) % 7;
        }

        return remainder == 0;
    }

    public static void main(String[] args) {
        String s = "00011100"; // 28

        if (!isBinary(s)) {
            System.out.println("Not a binary string");
            return;
        }

        if (divisibleBy7(s)) {
            System.out.println("Divisible by 7");
        } else {
            System.out.println("Not divisible by 7");
        }
    }
}



/*
run:

Divisible by 7

*/

 



answered Mar 1 by avibootz

Related questions

...