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;
    }
};

 

相关文章:

  • 2022-12-23
  • 2021-11-19
  • 2021-11-11
  • 2021-04-06
  • 2021-11-17
  • 2021-07-18
  • 2021-05-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-21
  • 2021-09-06
  • 2022-12-23
  • 2022-12-23
  • 2021-04-28
相关资源
相似解决方案