title: Daily practice (34): Addition without addition, subtraction, multiplication and division
categories:[Swords offer]
tags:[Daily practice]
date: 2022/03/09
Daily practice (34): Addition without addition, subtraction, multiplication and division
Write a function to calculate the sum of two integers. It is required that the four operators "+", "-", "*" and "/" should not be used in the function body.
Example:
Input: a = 1, b = 1
Output: 2
hint:
a, b can both be negative or 0
The result will not overflow a 32-bit integer
Source: LeetCode
Link: https://leetcode-cn.com/problems/bu-yong-jia-jian-cheng-chu-zuo-jia-fa-lcof
Method 1: Bit Operations
Algorithm flow:
a ^ b calculates the base of each bit in the binary of the 2 addends
a & b Calculate the carry of each digit in the binary of the 2 addends
(a & b) << 1 carry for carry logic, that is, * 2
int add(int a, int b) {
while (b != 0) {
int carry = a & b ; // 计算 进位
a ^= b; // 计算 本位
b = (unsigned)c << 1;
}
return a;
}
Method 2: Recursion
Addition = carry + non-carry part
Use XOR bit operation to represent the case of no carry 00=0 11=0 10=1 01=1
Use AND operation and left shift operation to represent the case of carry 11=10
Also perform a left shift operation in the loop
int add(int a, int b) {
// 后续用a表示非进位和,b表示进位,当进位为0,则表示计算结束
return b ? add(a ^ b, (unsigned)(a & b) << 1) : a;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。