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

1 Answer

0 votes
import java.util.regex.Pattern

// Checks whether a string contains only binary digits 0 or 1
fun isBinary(s: String): Boolean {
    val binary = Regex("^[01]+$")
    
    return binary.matches(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
*/

// Computes whether a binary string represents a number divisible by 7
fun divisibleBy7(s: String): Boolean {
    var remainder = 0

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

    return remainder == 0
}

fun main() {
    val s = "00011100" // 28

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

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



/*
run:

Divisible by 7

*/

 



answered Mar 1 by avibootz

Related questions

...