Monday, November 16, 2015

LinkedIn: Hashcode of a string in Java

Implement the hashcode() for a string in Java.

Code (Java):
import java.io.*;
import java.util.*;

/*
 * To execute Java, please define "static void main" on a class
 * named Solution.
 *
 * If you need more classes, simply define them inline.
 */

class Solution {
    public static int hashCode(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        int hash = 0;
        for (int i = 0; i < s.length(); i++) {
            hash = s.charAt(i) + 31 * hash;
        }
        
        return hash;
    }
    
    public static void main(String[] args) {
        String s = "call";
        int result = hashCode(s);
      
        System.out.println(result);
    }
}

No comments:

Post a Comment