Skip to content

Commit

Permalink
feat(solution): add solution 65
Browse files Browse the repository at this point in the history
Add two numbers
  • Loading branch information
yanglbme committed Dec 13, 2018
1 parent 6df7f69 commit d5c71d9
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
| 62 | [Last Number In Circle](/solution/剑指Offer/62_LastNumberInCircle) |
| 63 | [Maximal Profit](/solution/剑指Offer/63_MaximalProfit) |
| 64 | [Accumulate](/solution/剑指Offer/64_Accumulate) |
| 65 | [Add Two Numbers](/solution/剑指Offer/65_AddTwoNumbers) |


### 编程之美题集
Expand Down
49 changes: 49 additions & 0 deletions solution/剑指Offer/65_AddTwoNumbers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
## [不用加减乘除做加法](https://www.acwing.com/problem/content/81/)

### 题目描述
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、×、÷ 四则运算符号。

**样例**
```
输入:num1 = 1 , num2 = 2
输出:3
```

### 解法
先对两数进行异或,求得相加不仅位的结果。再循环对两数进行按位与运算,并左移一位,直至进位为 0。

```java
/**
* @author bingo
* @since 2018/12/13
*/

class Solution {

/**
* 不用加减乘除做加法
*
* @param num1 数1
* @param num2 数2
* @return 两数之和
*/
public int add(int num1, int num2) {
int sum, carry;
while (true) {
sum = num1 ^ num2;
carry = (num1 & num2) << 1;
num1 = sum;
num2 = carry;
if (num2 == 0) {
break;
}
}
return num1;
}
}
```


### 测试用例
1. 输入正数、负数、0。
28 changes: 28 additions & 0 deletions solution/剑指Offer/65_AddTwoNumbers/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* @author bingo
* @since 2018/12/13
*/

class Solution {

/**
* 不用加减乘除做加法
*
* @param num1 数1
* @param num2 数2
* @return 两数之和
*/
public int add(int num1, int num2) {
int sum, carry;
while (true) {
sum = num1 ^ num2;
carry = (num1 & num2) << 1;
num1 = sum;
num2 = carry;
if (num2 == 0) {
break;
}
}
return num1;
}
}

0 comments on commit d5c71d9

Please sign in to comment.