1 Topic Description

1.1 English Description

Given two integers a and b, return the sum of the two integers without using the operators + and -.

Example 1:

Input: a = 1, b = 2

Output: 3

Example 2:

Input: a = 2, b = 3

Output: 5

1.2 Chinese Description

Given two integers, sum them without using the +/- operators.

2 solution

2.1 Solution 1-bit operation

Use bitwise operations and recursion.

For example, 2 + 3 = 5; The binary of 5 is 0101.

The operation process is as follows:

  1. Two to the third is equal to the sum of two plus three, zero one.
2^3 is 0010 ^ 0011 ------- 0001Copy the code
  1. We find that 2&3 is equal to a regular number, and that a shift of 1 to the left is the carry of the final result.
2&3 is 0010&0011 -------- 0010Copy the code
  1. The result of 2&3 is shifted one bit to the left to get the carry of the final result.
0010 << 1 = 0100
Copy the code
  1. 0100 or 0001.
  0100
^ 0001
-------
  0101
Copy the code
  1. Loop until the carry number is 0.

2.2 code

Public static int getSum(int a,int b){if(b == 0) return a; Int i1 = a ^ b; Int i2 = a & b; Int i3 = i2 << 1; Return getSum(i1,i3); }Copy the code
Welcome to follow the personal public account, you can directly scan the following TWO-DIMENSIONAL code or wechat search “MAO Chat technology” to follow.