There is a business scenario where the id number is hashed. The last digit of the ID number may be an X. The id number can be treated as a base 11 data, and the transposition of the base 10 can be implemented in two ways, one from right to left:

        def computehash(x):
            res = 0
            reversedx = reversed(x)
            i = 0
            for c in reversedx:
                if c == 'x':
                    res += 10
                else:
                    res += int(c) * pow(10, i)
                i += 1
            return res
Copy the code

This implementation requires the calculation of the POW every time, and there is an optimized algorithm that avoids the calculation of the POW from left to right:

    def computehash(x):
        res = 0
        for c in x:
            if c == 'x':
                res = res * 10 + 10
            else:
                res = res * 10 + int(c)
        return res
Copy the code

Golang language version:

func computehash(x string) int { res := 0 for _,i := range x { if i == 'x' { res = res * 10 + 10 }else{ res = res * 10 +  int(i - '0') } } return res }Copy the code