File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ # 题目描述
2+ 写一个函数,求两个整数之和,要求在函数体内不得使用“+”、“-”、“\* ”、“\/ ”四则运算符号。
3+
4+ # 测试用例
5+ 输入整数、负数和0。
6+
7+ # 题目考点
8+ * 考察应聘者的发散思维能力。
9+ * 考察应聘者对二进制和位运算的理解。
10+
11+ # 解题思路
12+ 分为三步走:
13+ 1 . 利用位异或运算不考虑进位地加两个数
14+ 2 . 利用位与运算以及左移运算得到进制代表的值
15+ 3 . 将上面1,2的结果相加(即重复1,2运算,直到进位为0)
16+
17+ # 自己解题
18+ 位运算不熟!!!
19+ # 参考解题
20+ ``` Java
21+ /**
22+ * 不用加减乘除做加法
23+ *
24+ * @Author rex
25+ * 2018/9/18
26+ */
27+ public class Solution {
28+ /**
29+ * 位运算解题
30+ *
31+ * @param num1
32+ * @param num2
33+ * @return
34+ */
35+ public int add (int num1 ,int num2 ) {
36+ int sum, carry;
37+ do {
38+ // 1. 不考虑进位加
39+ sum = num1 ^ num2;
40+ // 2. 算出进位的值
41+ carry = (num1 & num2) << 1 ;
42+ num1 = sum;
43+ num2 = carry;
44+ } while (carry != 0 );
45+ // 3. 当没有进位的时候,num1就是最终的和
46+ return num1;
47+ }
48+ }
49+ ```
You can’t perform that action at this time.
0 commit comments