SHOW:
|
|
- or go back to the newest paste.
1 | - | public static String add(String bits1, String bits2){ |
1 | + | public static String add(String bits1, String bits2) { |
2 | - | bits1 = new StringBuilder(bits1).reverse().toString(); |
2 | + | int len1 = bits1.length(); |
3 | - | bits2 = new StringBuilder(bits2).reverse().toString(); |
3 | + | int len2 = bits2.length(); |
4 | - | |
4 | + | int max = Math.max(len1, len2); |
5 | - | StringBuilder result = new StringBuilder(); |
5 | + | StringBuilder result = new StringBuilder(1 + max); |
6 | - | |
6 | + | boolean one = false; |
7 | - | char q = '0';//for cases like: (1+1+0)=0 and 1, this (1) is stored in 1 |
7 | + | for (int i = 1; i <= max; i++) { |
8 | - | for(int i = 0;i < bits1.length();i++){ |
8 | + | final char c1 = len1 - i >= 0 ? bits1.charAt(len1 - i) : '0'; |
9 | - | char bit1 = bits1.charAt(i); |
9 | + | final char c2 = len2 - i >= 0 ? bits2.charAt(len2 - i) : '0'; |
10 | - | char bit2 = bits2.charAt(i); |
10 | + | if (('0' ^ c1) > 1 || ('0' ^ c2) > 1) |
11 | - | if(bit1 == '0'){ |
11 | + | throw new IllegalArgumentException(bits1 + " + " + bits2); |
12 | - | if(bit2 == '0'){ |
12 | + | if (c1 + c2 == 2 * '0') { |
13 | - | if(q == '0'){//(0+0+0)=0 and 0 |
13 | + | result.append(one ? '1' : '0'); |
14 | - | result.append('0'); |
14 | + | one = false; |
15 | - | q = '0'; |
15 | + | } else if (c1 + c2 == '0' + '1') { |
16 | - | }else if(q == '1'){//(0+0+1)=1 and 0 |
16 | + | result.append(one ? '0' : '1'); |
17 | - | result.append('1'); |
17 | + | } else if (c1 + c2 == 2 * '1') { |
18 | - | q = '0'; |
18 | + | result.append(one ? '1' : '0'); |
19 | - | } |
19 | + | one = true; |
20 | - | }else if(bit2 == '1'){ |
20 | + | } else |
21 | - | if(q == '0'){//(0+1+0)=1 and 0 |
21 | + | throw new IllegalArgumentException(bits1 + " + " + bits2); |
22 | - | result.append('1'); |
22 | + | } |
23 | - | q = '0'; |
23 | + | if (one) |
24 | - | }else if(q == '1'){//(0+1+1)=0 and 1 |
24 | + | result.append('1'); |
25 | - | result.append('0'); |
25 | + | return result.reverse().toString(); |
26 | - | q = '1'; |
26 | + | } |