1.基本解法——“+”
可多组输入,每一行有两个数a,b 0<a,b<1000000 ,每行输出一个结果。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
// 注意,如果输入是多个测试用例,请通过while循环处理多个测试用例
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a + b);
}
}
}
2.另类加法——“位运算”
编写一个函数,将两个数字相加。不得使用+或其他算数运算符。
即使用位运算
import java.util.Scanner;
public class Main1 {
public static int addAB(int A, int B){
if(B==0){
return A;
}else{
int sum = A^B; //只相加不进位
int jw = (A&B)<<1; //只进位不相加
return addAB(sum,jw);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println(addAB(a,b));
}
}
思路:二进制加法特点。
位的异或运算跟求'和'的结果一致:
异或 1^1=0 1^0=1 0^0=0
求和 1+1=0 1+0=1 0+0=0
位的与运算跟求'进位‘的结果一致:
位与 1&1=1 1&0=0 0&0=0
进位 1+1=1 1+0=0 0+0=0
于是可以用异或运算和与运算来表示加法