Skip to content

Instantly share code, notes, and snippets.

@ramonaharrison
Created November 15, 2015 16:44
Show Gist options
  • Save ramonaharrison/c544f2666e499b41043d to your computer and use it in GitHub Desktop.
Save ramonaharrison/c544f2666e499b41043d to your computer and use it in GitHub Desktop.
Data Representation HW
package nyc.c4q.ramonaharrison;
/**
* Access Code 2.1
* Ramona Harrison
*/
public class BinaryAddition {
public static void main(String[] args) {
String s1 = Integer.toString(134,2);
String s2 = Integer.toString(562,2);
System.out.println(addBinaryNumbers(s1, s2));
String s3 = Integer.toString(51,2);
String s4 = Integer.toString(-8,2);
System.out.println(addBinaryNumbers(s3, s4));
System.out.println(Integer.toOctalString(52));
}
public static String addBinaryNumbers(String binary1, String binary2) {
if (binary1 == null || binary2 == null) return "";
int first = binary1.length() - 1;
int second = binary2.length() - 1;
StringBuilder stringBuilder = new StringBuilder();
int carry = 0;
while (first >= 0 || second >= 0) {
int sum = carry;
if (first >= 0) {
sum += binary1.charAt(first) - '0';
first--;
}
if (second >= 0) {
sum += binary2.charAt(second) - '0';
second--;
}
carry = sum >> 1;
sum = sum & 1;
stringBuilder.append(sum == 0 ? '0' : '1');
}
if (carry > 0)
stringBuilder.append('1');
stringBuilder.reverse();
return String.valueOf(stringBuilder);
}
public static int countOnes(String bitstring) {
int ones = 0;
for (int i = 0; i < bitstring.length(); i++) {
if (bitstring.charAt(i) == '1') {
ones++;
}
}
return ones;
}
public static boolean isPalindrome(String bitstring) {
return bitstring.equals(new StringBuilder(bitstring).reverse().toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment