diff --git a/Write-hashtable-in-php/HashTable.php b/Write-hashtable-in-php/HashTable.php index cac2a67..e3dfcd1 100644 --- a/Write-hashtable-in-php/HashTable.php +++ b/Write-hashtable-in-php/HashTable.php @@ -5,6 +5,8 @@ class HashTale private $size = 0; private $container = null; + private $bigPrime = 1861; + public function __construct($size=1000) { // 哈希表的大小 @@ -21,8 +23,26 @@ private function getItemDefine() ); return $item; + } + + public function hashNum($key) + { + // $key不能太长,$this->bigPrime也不能太大,不然会引起整数溢出 + + $hashNum = 0; + $keyLen = strlen($key); + + // 这里的**幂运算你也可以用位移来实现 + for ($i=0; $i<$keyLen; $i++) { + $hashNum += ($this->bigPrime ** ($keyLen - ($i+1))) * ord($key[$i]); + } + + $hashNum = $hashNum % $this->size; + + return $hashNum; } } -$hashTable = new HashTale(2); -var_dump($hashTable); \ No newline at end of file +$hashTable = new HashTale(); + +var_dump($hashTable->hashNum('hello')); \ No newline at end of file