Created
January 4, 2014 05:26
-
-
Save zjor/8252070 to your computer and use it in GitHub Desktop.
Implementation of standard hashing algorithm in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.example; | |
public class Main { | |
private static long power(long x, long y) { | |
if (y == 0) { | |
return 1; | |
} else if (y == 1) { | |
return x; | |
} | |
if ((y & 0x1) == 0) { | |
return power(x * x, y >> 1); | |
} else { | |
return x * power(x, y - 1); | |
} | |
} | |
private static long hash(String input) { | |
long hash = 0L; | |
for (int i = 0; i<input.length(); i++) { | |
hash += power(31, input.length() - i - 1) * input.charAt(i); | |
} | |
return hash % power(2, 32); | |
} | |
public static void main(String[] args) throws InterruptedException { | |
String input = "hello world"; | |
System.out.println(input.hashCode()); | |
System.out.println(hash(input)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment