How to check if every digit in a number appears only once in Kotlin

1 Answer

0 votes
// n % 10 extracts the last digit.
// 1 shl digit creates a bitmask for that digit.
// (mask and bit) checks whether the bit for this digit is already set.
// Mark the digit as seen: mask = mask or bit; This sets the bit for the current digit.

fun allDigitsUnique(n: Int): Boolean {
    var mask = 0
    var x = n

    while (x > 0) {
        val digit = x % 10
        val bit = 1 shl digit

        if ((mask and bit) != 0) return false // digit already seen
        mask = mask or bit

        x /= 10
    }

    return true
}

fun main() {
    var n = 123456
    println(if (allDigitsUnique(n)) "Unique" else "Not unique")

    n = 123452
    println(if (allDigitsUnique(n)) "Unique" else "Not unique")
}



/*
run:

Unique
Not unique

*/

 



answered Feb 27 by avibootz
...