Java 8(完整程序),257字节
interface M{static void main(String[]a)throws Exception{int i=0,j;while((j=System.in.read())>10)i=i*10+j-48;System.out.print(L(i));}static String L(int i){if(i==0)return "0";String s=Integer.toString(i,2);return "1"+L(s.length()-1)+s.substring(1);}}
带有解释的可读版本(主要是递归):
interface M {
static void main(String[]a) throws Exception { // Using Exception is unadvised in real coding, but this is Code Gold
int i = 0, j; // i stores the input; j is a temporary variable
while ((j = System.in.read()) > 10) // Read the input to j and stop if it is a newline. Technically this stops for tabulators as well, but we shouldn't encounter any of those...
i = i * 10 + j - 48; // Looping this step eventually reads the whole number in from System.in without using a reader (those take up a lot of bytes)
System.out.print(L(i)); // Make a method call
}
static String L(int i) { // This gets the actual Levenshtein Code
if (i == 0)
return "0"; // The program gets a StackOverflowException without this part
String s = Integer.toString(i, 2); // Shorter than toBinaryString
return "1" + L(s.length() - 1) + s.substring(1); // Write in the first character (which is always a one), followed by the next L-code, followed by the rest of the binary string
}
}
编辑1:保存8个字节:二进制字符串的第一个字符始终为 1;因此,不是使用,而是s.charAt(0)
更好的选择"1"
。
±
而不是函数来节省一些字节f
。