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

1 Answer

0 votes
object UniqueDigitsProgram {

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

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

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

      if ((mask & bit) != 0) return false // digit already seen
      mask |= bit

      x /= 10
    }

    true
  }

  def main(args: Array[String]): Unit = {
    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
edited Feb 27 by avibootz
...