Integer.toBinaryString(int i)
Hasło na wieczór: bitmask
XOR
0^0 = 0
0^1 = 1
1^0 = 1
1^1=0
bit XOR 0 nie zmienia bitu
bit XOR 1 neguje bit
Zrób XOR z maską 0 na pozycjach bitów nieparzystych, jeden na pozycjach bitów parzystych.
@RunWith(Parameterized.class)
public class XORParameterizedTest {
@Parameterized.Parameter(value = 0)
public int a;
@Parameterized.Parameter(value = 1)
public int b;
@Parameterized.Parameter(value = 2)
public int xor;
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{0, 0, 0},
{0, 1, 1},
{1, 0, 1},
{0, 0, 0}
});
}
@Test
public void shouldDoXOR() {
int result = a ^ b;
assertThat(result, is(equalTo(xor)));
}
}
Wyświetlanie od tyłu dasz radę bez podpowiedzi. Zwykła pętla for odliczana -1 od końca tablicy-stringa bedzie OK
Nie przejmuj się zadaniem, sam musiałem wystackoverfloować ;) Integer.toBinaryString i jak się oznacza w Java XOR, to jest ^
public class XORTest {
@Test
public void shouldDo0XOR0() {
int a = 10;
int b = 7;
int result = a ^ b;
assertThat(result, is(equalTo(13)));
assertThat(Integer.toBinaryString(a), is(equalTo("1010")));
assertThat(Integer.toBinaryString(b), is(equalTo("111")));
assertThat(Integer.toBinaryString(result), is(equalTo("1101")));
}
}
W XOR nie ma przeniesienia nadmiaru na starszy bit.
Wyświetlanie
public class XOR {
public static String mirrorBinaryNumber(String binary) {
if (binary == null || "".equals(binary)) {
return binary;
}
return recReverse(binary, binary.length() - 1);
}
private static String recReverse(String binary, int position) {
if (position == 0) {
return "" + binary.charAt(position);
} else {
return "" + binary.charAt(position) + recReverse(binary, position - 1);
}
}
}
public class XORMirroringTest {
@Test
public void shouldReverseBasicCases() {
assertThat(XOR.mirrorBinaryNumber(null), is(equalTo(null)));
assertThat(XOR.mirrorBinaryNumber(""), is(equalTo("")));
assertThat(XOR.mirrorBinaryNumber("0"), is(equalTo("0")));
assertThat(XOR.mirrorBinaryNumber("1"), is(equalTo("1")));
assertThat(XOR.mirrorBinaryNumber("00"), is(equalTo("00")));
assertThat(XOR.mirrorBinaryNumber("11"), is(equalTo("11")));
assertThat(XOR.mirrorBinaryNumber("01"), is(equalTo("10")));
assertThat(XOR.mirrorBinaryNumber("10"), is(equalTo("01")));
assertThat(XOR.mirrorBinaryNumber("10110001101"), is(equalTo("10110001101")));
}
}
I do poćwiczenia w/s pyt. na priv.
public class XOR {
public static String mirrorBinaryNumber(String binary) {
if (binary == null || "".equals(binary)) {
return binary;
}
return recTailReverse(binary, binary.length() - 1, "");
}
private static String recTailReverse(String binary, int position, String acc) {
if (position < 0) {
return acc;
} else {
return recTailReverse(binary, position - 1, acc + binary.charAt(position));
}
}
}
Test zostaje ten sam