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

1 Answer

0 votes
package main

import (
    "fmt"
    "regexp"
)

func isBinary(s string) bool {
    binary := regexp.MustCompile(`^[01]+$`)
    
    return binary.MatchString(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
*/

// bool divisibleBy7(const std::string& s) {
func divisibleBy7(s string) bool {
    remainder := 0

    for _, c := range s {
        remainder = (remainder*2 + int(c-'0')) % 7
    }

    return remainder == 0
}

func main() {
    s := "00011100" // 28

    if !isBinary(s) {
        fmt.Println("Not a binary string")
        return
    }

    if divisibleBy7(s) {
        fmt.Println("Divisible by 7")
    } else {
        fmt.Println("Not divisible by 7")
    }
}


/*
run:

Divisible by 7

*/

 



answered Mar 1 by avibootz

Related questions

...