Skip to content

Instantly share code, notes, and snippets.

@arthurpalves
Last active February 5, 2016 16:26
Show Gist options
  • Save arthurpalves/ef16eb1825bc586d10f0 to your computer and use it in GitHub Desktop.
Save arthurpalves/ef16eb1825bc586d10f0 to your computer and use it in GitHub Desktop.
Negate a negative based binary (base -2) using Two's Complement Annotation.
package com.codility.tasks;
/*
Negate a negative based binary (base -2) using Two's Complement Annotation.
Given a base -2 number splitted into a primitive array of ints (int[]), return it's negation.
EXAMPLES:
INPUT: [0,1,0,0,1,1,1] // Decimal 39.
OUTPUT: [1,0,1,1,0,0,1] // Decimal -39.
INPUT: [1,0,0,1,0,1,1] // Decimal -53.
OUTPUT: [0,1,1,0,1,0,1] // Decimal 53.
*/
import java.util.Arrays;
/*
@author Arthur Alves < hello@arthuralves.com >
*/
public class NegaBinary {
public static void main(String[] args) {
int[] binary = new int[]{0,1,0,0,1,1,1}; // Decimal 39
System.out.println("Negation: "+Arrays.toString(solution(binary)));
}
public static int fromBinaryToInt(int B[]) {
String stringBinary = "";
for (int digit: B) {
stringBinary = stringBinary + digit;
}
long l = Long.parseLong(stringBinary, 2);
int i = (int) l;
return i;
}
public static int[] fromIntToBinary(int value, int size) {
String binaryString = Integer.toBinaryString(value);
binaryString = binaryString.substring(binaryString.length()-size);
int[] binaryArray = new int[binaryString.length()];
for (int i=0; i< binaryString.length(); i++) {
binaryArray[i] = (int)Long.parseLong(binaryString.substring(i, i+1));
}
return binaryArray;
}
public static int[] solution(int[] A) {
int value = fromBinaryToInt(A);
return fromIntToBinary(-value, A.length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment