1,自己写的又长又臭的代码,也能AC,但是太丑了。主要是通过二进制来算。
public static int addAB(int a, int b){ int res = 0; String str1 = Integer.toBinaryString(a); String str2 = Integer.toBinaryString(b); ArrayList<Integer> list = new ArrayList(); int digit = 0; int cur = 0; int i = str1.length()-1; int j = str2.length()-1; while(i >= 0 && j >= 0){ int tmp = 0; if(str1.charAt(i) == ‘1‘){ System.out.println("here"); if(str2.charAt(j) == ‘1‘){ if(cur == 1){ tmp = 1; digit = 1; } else{ tmp = 0; digit = 1; } } else{ if(cur == 1){ digit = 1; tmp = 0; } else{ digit = 0; tmp = 1; } } } else{ if(str2.charAt(j) == ‘1‘){ if(cur == 1){ digit = 1; tmp = 0; } else{ tmp = 1; digit = 0; } } else{ if(cur == 1){ digit = 0; tmp = 1; } else{ digit = 0; tmp = 0; } } } cur = digit; digit = 0; list.add(tmp); i--; j--; } while(i >= 0){ int tmp = 0; if(str1.charAt(i) == ‘1‘){ if(cur == 1){ tmp = 0; digit = 1; } else{ tmp = 1; digit = 0; } } else{ if(cur == 1){ tmp = 1; digit = 0; } else{ digit = 0; tmp = 0; } } list.add(tmp); cur = digit; digit = 0; i--; } while(j >= 0){ int tmp = 0; if(str2.charAt(j) ==‘1‘){ if(cur == 1){ tmp = 0; digit = 1; } else{ tmp = 1; digit = 0; } } else{ if(cur == 1){ tmp = 1; digit = 0; } else{ digit = 0; tmp = 0; } } list.add(tmp); cur = digit; digit = 0; j--; } if(cur == 1){ list.add(1); } System.out.println(list); int num = 0; String str = new String(); for(int k = list.size()-1;k >= 0; k--){ str += list.get(k); } System.out.println(str); return Integer.valueOf(str,2) ; }
2,CC150课本上的答案:
原文:http://www.cnblogs.com/yueyebigdata/p/5109389.html