思路
hashcode("abcd") = (ascii(a) * 333 + ascii(b) * 332 + ascii(c) *33 + ascii(d)) % HASH_SIZE
= (97* 333 + 98 * 332 + 99 * 33 +100) % HASH_SIZE
= 3595978 % HASH_SIZE
取模运算:
(a * b) % p = ((a % p) * (b % p)) % p
Python
class Solution:
"""
@param: key: A string you should hash
@param: HASH_SIZE: An integer
@return: An integer
"""
def hashCode(self, key, HASH_SIZE):
# write your code here
res = 0
for hash_ch in key:
res *= 33
res += ord(hash_ch)
res %= HASH_SIZE
return res
key, HASH_SIZE = "abcdefghijklmnopqrstuvwxyz", 2607
s = Solution()
print(s.hashCode(key, HASH_SIZE))