LintCode: Hash Function
C++
(1)模运算(百度百科)
(a±b)%p = (a%p±b%p)%p
(a*b)%p = (a%p*b%p)%p
(a^b)%p = ((a%p)^b)%p
(2)使用long型
(3)magic number 33
(4)循环公式
class Solution { public: /** * @param key: A String you should hash * @param HASH_SIZE: An integer * @return an integer */ int hashCode(string key, int HASH_SIZE) { // write your code here int len = key.length(); int magic = 1; long sum = (int)key[0]; for (int i = 1; i < len; i++) { sum = (sum*33)%HASH_SIZE + (int)key[i]; } return (int)sum%HASH_SIZE; } };
找我内推: 字节跳动各种岗位
作者:
ZH奶酪(张贺)
邮箱:
cheesezh@qq.com
出处:
http://www.cnblogs.com/CheeseZH/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。