Reputation: 21
I am trying to do the hashcode calculation manually of string as it says the formula for String hashcode as " s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]", As below
public static void main(String[] args) {
String str1 = new String("A");
double hc = 0;
for (int i = 0; i < str1.length(); i++) {
int iv = (byte) str1.charAt(i);
hc = hc + Math.pow((iv * 31), (str1.length() - 1 - i));
}
System.out.println(hc); // 1.0
System.out.println(str1.hashCode()); // 65
}
The value of 'hc' is 1.0 because java converts byte to int value as per rules. but the answer i am looking for is 65. How to copy byte value as it is to an int variable.
Upvotes: 2
Views: 109
Reputation: 66
So from far what i see u make mistake in function what i mean by that:
Math.pow((iv * 31), (str1.length() - 1 - i))
is equal => (65 * 31)^(1[str.lenght] - 1 - 0[i value])
what gives something like (65*31) ^ 0 what gives 1 but you are looking for expression 65 * (31 ^ 0) [in conclusion] so the function should looks like
Math.pow((31), (str1.length() - 1 - i)) * iv
what i guess gonna give 65
Upvotes: 1