import Foundation
// n % 10 extracts the last digit.
// 1 << digit creates a bitmask for that digit.
// mask & bit 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.
func allDigitsUnique(_ n: Int) -> Bool {
var n = n
var mask = 0
while n > 0 {
let digit = n % 10
let bit = 1 << digit
if (mask & bit) != 0 { return false } // digit already seen
mask |= bit
n /= 10
}
return true
}
let tests = [123456, 123452]
for value in tests {
print(allDigitsUnique(value) ? "Unique" : "Not unique")
}
/*
run:
Unique
Not unique
*/