18.1---不用加号的加法(CC150)
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课本上的答案。写的非常漂亮,一定要记住了。
思路,1,如果只加不进位,1+1=0,1,0相加1.0+0=0;2,如果看什么时候进位,11的时候。
所以就是a^b,a&b。但进位是往前的,所以,a&b<<1.
答案:
public static int addAB(int a, int b) { // write code here if(b == 0) return a; int sum = a ^ b;//只加不进位 int carry = (a & b) << 1;//因为只有1,1,时候才进位。 return addAB(sum,carry); }