题意:输入两个数a和b,输出二者之和,要求不使用“+”和“-”
思路:计算机中的负数使用补码表示(绝对值表示,按位求反,末位加1)
按位运算(数字逻辑设计)1 op 1 = 1 0; 1 op 0 = 1; 0 op 1; 0 op 0 = 0
异或:无需进位的位(其他)“^”
与: 需要进位的位(第一种)"&"
或:“|”
非:“!”
public int getSum(int a, int b) {
int carry;
while(a != 0){
carry = a & b;
b = a ^ b;
a = carry << 1;
}
return b;
} //iterative
public int getSum(int a, int b) {
int res, res1, res2;
/*
* Integer.MAX_VALUE Integer.MIN_VALUE
*/
if(a == 0) return b;
else return getSum((a&b)<<1, a^b);
} //recursive
//alighment: little-endian
public static byte[] conv(int x){
byte res[] = new byte[4];
int offset = 0;
for(int i = 0; i < 4; i++ ){
res[i] = (byte)((x >> offset) & 0xff);
offset += 8;
}
return res;
}
public static int conv(byte[] x){
if(x.length != 4) return -1;
int res = 0;
int offset = 0;
for(int i = 0; i < x.length; i++){
res += (x[i] & 0xff) << offset;
offset += 8;
}
return res;
}
//unit test
public static void main(String args[]) throws FileNotFoundException{
int arr[];
String st[];
arr = new int[2];
/*
int x1;
byte bt[] = conv(x);
System.out.println(bt[0] + " " + bt[1] + " " + bt[2] + " " + bt[3]);
x1 = conv(bt);
System.out.println(x1);
*/
Scanner sc = new Scanner(new File("test.txt"));
while(sc.hasNextLine()){
st = sc.nextLine().split(" ");
for(int i = 0; i < st.length; i++) {
//st.length == 2
arr[i] = Integer.parseInt(st[i]);
System.out.print(arr[i] + " ");
}
getSum(arr[0], arr[1]);
System.out.println(getSum(arr[0], arr[1]));
System.out.println("***************************");
}
sc.close();
}