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奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/5105576.html,如需转载请自行联系原作者