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

1 Answer

0 votes
import Foundation

// Checks whether a string contains only binary digits 0 or 1
func isBinary(_ s: String) -> Bool {
    // Swift's modern regex literal
    let binary = try! Regex("^[01]+$")
    return s.wholeMatch(of: binary) != nil
}

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

// Computes whether a binary string represents a number divisible by 7
func divisibleBy7(_ s: String) -> Bool {
    var remainder = 0

    for c in s {
        remainder = (remainder * 2 + (c == "1" ? 1 : 0)) % 7
    }

    return remainder == 0
}

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

    if !isBinary(s) {
        print("Not a binary string")
        return
    }

    if divisibleBy7(s) {
        print("Divisible by 7")
    } else {
        print("Not divisible by 7")
    }
}

main()



/*
run:

Divisible by 7

*/

 



answered Mar 1 by avibootz

Related questions

...