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

1 Answer

0 votes
package main

import (
    "fmt"
)

// 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 {
    mask := 0

    for n > 0 {
        digit := n % 10
        bit := 1 << digit

        if mask&bit != 0 {
            return false // digit already seen
        }
        mask |= bit

        n /= 10
    }

    return true
}

func main() {
    n := 123456
    fmt.Println(func() string {
        if allDigitsUnique(n) {
            return "Unique"
        }
        return "Not unique"
    }())

    n = 123452
    fmt.Println(func() string {
        if allDigitsUnique(n) {
            return "Unique"
        }
        return "Not unique"
    }())
}



/*
run:

Unique
Not unique

*/

 



answered Feb 27 by avibootz
...