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

1 Answer

0 votes
#include <stdio.h>

int is_binary(const char *s) {
    if (s[0] == '\0') return 0;  // empty string not allowed

    for (int i = 0; s[i] != '\0'; i++) {
        if (s[i] != '0' && s[i] != '1')
            return 0;
    }
    
    return 1;
}

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

int divisible_by_7(const char *s) {
    int remainder = 0;

    for (int i = 0; s[i] != '\0'; i++) {
        remainder = (remainder * 2 + (s[i] - '0')) % 7;
    }

    return remainder == 0;
}

int main(void) {
    const char *s = "00011100";  // 28

    if (!is_binary(s)) {
        printf("Not a binary string\n");
        return 0;
    }

    if (divisible_by_7(s)) {
        printf("Divisible by 7\n");
    } else {
        printf("Not divisible by 7\n");
    }

    return 0;
}



/*
run:

Divisible by 7

*/

 



answered Mar 1 by avibootz
edited Mar 1 by avibootz

Related questions

...