int myPow(int number, int n)
{
if(n == 0)
return 1;
else {
return (number * myPow(number, n-1));
}
}
unsignedint hashmap::hashStr(charconst * const str)
{
unsignedint hash = 0;
int n = strlen(str);
for(int i = 0; i < n; i++)
{
int x = ((n-1)-i);
hash += static_cast<int>(str[i])*myPow(32, x);
}
return hash;
}
I think there's a better way to do this without writting the pow function and using recursion, probably by factoring out the equation but I'm lost as to how I would do that.
int result = 1;
for(int i = 0; i < n; i++) result *= number;
Also, since all powers form a progression, you could simply add the calculation in your for loop:
1 2 3 4 5 6 7 8 9
unsignedint hash = 0;
int n = strlen(str);
int pow = 1;
for(int i = 0; i < n; i++){//you may want to make this i=n-1; i>= 0; i--
//it doesn't make any real deference though.
pow *= 31;
hash += static_cast<int>(str[i])*pow;
}
return hash;