public static String addiere(List<String> list) {
StringBuilder res = new StringBuilder();
for (String str : list) {
System.out.println("str = " + str);
int res_idx = res.length() - 1;
int carry = 0;
for (int i = str.length() - 1; i >= 0; i--, res_idx--) {
if (res_idx < 0) {
res.insert(0, '0');
res_idx++;
}
char c = (char) ((carry ^ str.charAt(i) - '0' ^ res.charAt(res_idx) - '0') + '0');
carry = carry + (str.charAt(i) - '0') + (res.charAt(res_idx) - '0') >= 2 ? 1 : 0;
res.setCharAt(res_idx, c);
}
System.out.println("res = " + res);
if (carry == 1) {
for (; res_idx >= 0 && res.charAt(res_idx) == '1'; res_idx--) {
res.setCharAt(res_idx, '0');
}
if (res_idx < 0) {
res.insert(0, '1');
} else {
res.setCharAt(res_idx, '1');
}
}
System.out.println("res = " + res);
System.out.println();
}
return res.toString();
}
public static void main(String[] args) {
System.out.println(addiere(Arrays.asList(
Integer.toBinaryString(1),
Integer.toBinaryString(2),
Integer.toBinaryString(3),
Integer.toBinaryString(4),
Integer.toBinaryString(5),
Integer.toBinaryString(6),
Integer.toBinaryString(7),
Integer.toBinaryString(3))));
// Erstelle 1000x eine Liste mit je 10 Elementen und prüfe, ob addiere das richtige Ergebnis liefert
Random ran = new Random();
for (int i = 0; i < 1000; i++) {
ArrayList<String> lst = new ArrayList<String>();
int sum = 0;
for (int j = 0; j < 10; j++) {
int r = ran.nextInt(1000);
lst.add(Integer.toBinaryString(r));
sum += r;
}
if (!addiere(lst).equals(Integer.toBinaryString(sum))) {
System.err.println("Failure!");
System.exit(0);
}
}
}