一家公司向我发出了以下编码挑战,要求我编写编码和解码功能:
编码:此函数需要接受14位范围-8192..+8191中的有符号整数,并返回一个4个字符串。编码过程如下:

解码:您的解码函数应该在输入时接受两个字节,这两个字节都在0x00..0x7F范围内,并将它们重新组合以在-8192..+8191之间返回相应的整数。

以下是我对这两种功能的解决方案:
public static String encode(int num){
if(num < -8192 || num > 8191) {
throw new IllegalArgumentException("This function only takes ints within the 14-bit range (-8192 to 8191)");
} else {
//step 1
//System.out.println("Unencoded Decimal Value: "+ num);
num += 8192;
//System.out.println("Intermediate Decimal: " + num);
//step 2
String numString = Integer.toHexString(num);
//System.out.println("Intermediate Hex: " + numString);
//step 3
String theBinary = Integer.toBinaryString(Integer.parseInt(numString,16));
while(theBinary.length() < 14){
String zero = "0";
zero += theBinary;
theBinary = zero;
}
//Build the updated Binary
String newBinary = "";
for(int i=theBinary.length() -1; i>=0; i--){
newBinary += theBinary.charAt(i);
if(i== 7 || i == 0){
newBinary += "0";
}
}
newBinary = new StringBuilder(newBinary).reverse().toString();
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(Integer.parseInt(newBinary,2)));
while(sb.length() < 4) {
sb.insert(0, '0'); // pad with leading zero if needed
}
String hex = sb.toString();
System.out.println("The Encoded Hex: " + hex);
System.out.println();
return hex;
}
}
public static int decode(byte byte1, byte byte2){
if(byte1 < 0x00 || byte2 < 0x00 || byte1 > 0x7F || byte2 > 0x7F){
throw new IllegalArgumentException("This function only takes bytes between 0x00 and 0x7F");
}
//Append Zeros
String pt1 = Integer.toBinaryString(byte1);
while(pt1.length() < 7){
String zero = "0";
zero += pt1;
pt1 = zero;
}
//Append Zeros
String pt2 = Integer.toBinaryString(byte2);
while(pt2.length() < 7){
String zero = "0";
zero += pt2;
pt2 = zero;
}
String fullBinary = pt1 + pt2;
//System.out.println("Full Binary: "+fullBinary);
int decimalValue = Integer.parseInt(fullBinary, 2);
//System.out.println("Decimal Value: "+decimalValue);
int originalValue = decimalValue - 8192;
System.out.println("Original Value: " + originalValue);
//System.out.println();
return originalValue;
}我得知,这一解决办法“没有显示出所需的专门知识水平”。在挑战中发出的唯一要求是编写函数并返回指定的值(它会这样做),并快速完成它(它确实这样做)。我的主要问题是,我可以在哪里改进这个代码,以“展示更多的专业知识”。我只是在寻找一个入门级的编程职位,但我一直得到这样的响应,即使在编写完成任务的代码时,这种响应也是模糊的。
发布于 2014-09-11 20:22:57
你太认真地承担这个任务了。所有的二进制内容只是为了解释,它并不意味着要实现。
现在没时间评论了..。晚些时候再做。同时学习有关位操作的知识。
public static String encode(int num) {
final int translated = num + 8192;
final int lowSevenBits = translated & 0x007F; // 0b0000_0000_0111_1111
final int highSevenBits = translated & 0x3F80; // 0b0011_1111_1000_0000
final int composed = lowSevenBits + (highSevenBits << 1);
return String.format("%04X", composed);
}您还应该始终编写测试:
public void test() {
assertEquals("4000", encode(0));
assertEquals("0000", encode(-8192));
assertEquals("7F7F", encode(8191));
assertEquals("5000", encode(2048));
assertEquals("2000", encode(-4096));
}https://codereview.stackexchange.com/questions/62682
复制相似问题