# 8ms(beat 100%) Java Solution

• ``````public class Codec {

// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
StringBuilder sb=new StringBuilder();
for(String s:strs){
sb=sb.append((char)(s.length()>>16)).append((char)s.length()).append(s);
}
return sb.toString();
}

// Decodes a single string to a list of strings.
public List<String> decode(String s) {
ArrayList<String> result=new ArrayList();
char[] cc=s.toCharArray();
for(int i=0,num=0;i<cc.length;i=i+num){
num=((0+cc[i])<<16)+cc[++i];
}
return result;
}
``````

}

• Can you please explain your logic? why are you shifting the length >> by 16?

• @mananshah007 I guess this line:num=((0+cc[i])<<16)+cc[++i], actually get the length of string.

sb.append((char)(s.length()>>16)).append((char)s.length()). I guess this line is to convert length of str into 2 chars.

• @mananshah007
I changed the code a little bit, there is no "length >> 16" and it works as well.
public String encode(List<String> strs) {
StringBuilder sb=new StringBuilder();
for(String s:strs)
sb=sb.append((char)s.length()).append(s);
return sb.toString();}

• @QunWu Would that be safe if we just convert the length of the string to a char and then convert it back to an integer? What if we have a string with length for example, as 2^23?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.