SHARE
TWEET

binary addition

DulcetAirman Aug 3rd, 2018 (edited) 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public static String add(String bits1, String bits2) {
  2.     int len1 = bits1.length();
  3.     int len2 = bits2.length();
  4.     int max = Math.max(len1, len2);
  5.     StringBuilder result = new StringBuilder(1 + max);
  6.     boolean one = false;
  7.     for (int i = 1; i <= max; i++) {
  8.         final char c1 = len1 - i >= 0 ? bits1.charAt(len1 - i) : '0';
  9.         final char c2 = len2 - i >= 0 ? bits2.charAt(len2 - i) : '0';
  10.         if (('0' ^ c1) > 1 || ('0' ^ c2) > 1)
  11.             throw new IllegalArgumentException(bits1 + " + " + bits2);
  12.         if (c1 + c2 == 2 * '0') {
  13.             result.append(one ? '1' : '0');
  14.             one = false;
  15.         } else if (c1 + c2 == '0' + '1') {
  16.             result.append(one ? '0' : '1');
  17.         } else if (c1 + c2 == 2 * '1') {
  18.             result.append(one ? '1' : '0');
  19.             one = true;
  20.         } else
  21.             throw new IllegalArgumentException(bits1 + " + " + bits2);
  22.     }
  23.     if (one)
  24.         result.append('1');
  25.     return result.reverse().toString();
  26. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top