Skip to content

Commit 5eae125

Browse files
committed
dont need a window, just keep track of carry
1 parent d99e1de commit 5eae125

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

src/java/BinaryArithmetic.java

+9-13
Original file line numberDiff line numberDiff line change
@@ -52,36 +52,32 @@ static String addBinaryStrings(String a, String b) throws Exception {
5252
result[i] = 0;
5353
}
5454

55-
//itterate using a window of relevant info
56-
int previousResult = 0;
55+
//keep track of the carry
56+
int carry = 0;
5757
for (int current = maxLength - 1; current >= 0; current--) {
58-
int previous = current - 1;
59-
if (previous < -1) {
60-
break;
61-
}
6258
System.out.println("Working on " + current);
6359
char acurrent = a.charAt(current);
6460
char bcurrent = b.charAt(current);
6561

6662
System.out.println("Sum of " + acurrent + " + " + bcurrent + " =");
67-
int sum = addChar(acurrent, bcurrent) + previousResult;
63+
int sum = addChar(acurrent, bcurrent) + carry;
6864
System.out.println(" = " + sum);
6965
if (sum == 3) {
7066
result[current] = 1;
71-
previousResult = 1;
72-
System.out.println(" Carrying further " + previousResult);
67+
carry = 1;
68+
System.out.println(" Carrying further " + carry);
7369
} else if (sum == 2) {
7470
result[current] = 0;
75-
previousResult = 1;
76-
System.out.println(" Carrying " + previousResult);
71+
carry = 1;
72+
System.out.println(" Carrying " + carry);
7773
} else {
7874
result[current] = sum;
79-
previousResult = 0;
75+
carry = 0;
8076
}
8177
}
8278

8379
String asString = "";
84-
if (previousResult == 1) {
80+
if (carry == 1) {
8581
asString += "1";
8682
}
8783
for (int i = 0; i < maxLength; i++) {

0 commit comments

Comments
 (0)