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

1 Answer

0 votes
// 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.

fn all_digits_unique(mut n: i32) -> bool {
    let mut 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;
    }

    true
}

fn main() {
    let mut n = 123456;
    println!("{}", if all_digits_unique(n) { "Unique" } else { "Not unique" });

    n = 123452;
    println!("{}", if all_digits_unique(n) { "Unique" } else { "Not unique" });
}



/*
run:

Unique
Not unique

*/

 



answered Feb 27 by avibootz
...