LeetCode题解371.sum-of-two-integers

题目地址

https://leetcode.com/problems/sum-of-two-integers/description/

题目描述

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example 1:

Input: a = 1, b = 2
Output: 3
Example 2:

Input: a = -2, b = 3
Output: 1

思路

不能使用加减法来求加法。 我们只能朝着位元算的角度来思考了。

由于异或相同则位0,不同则位1,因此我们可以把异或看成是一种不进位的加减法。

LeetCode题解371.sum-of-two-integers

由于全部位1则位1,否则位0,因此我们可以求与之后左移一位来表示进位。

LeetCode题解371.sum-of-two-integers

然后我们对上述两个元算结果递归求解即可。 递归的结束条件就是其中一个为0,我们直接返回另一个。

关键点解析

  • 位运算
  • 异或是一种不进位的加减法
  • 求与之后左移一位来可以表示进位

代码

/*
 * @lc app=leetcode id=371 lang=javascript
 *
 * [371] Sum of Two Integers
 */
/**
 * @param {number} a
 * @param {number} b
 * @return {number}
 */
var getSum = function(a, b) {
    if (a === 0) return b;

    if (b === 0) return a;

    return getSum(a ^ b, (a & b) << 1);
};
LeetCode题解1879. Two Sum VII

给定一个已经 按绝对值升序排列 的数组,找到两个数使他们加起来的和等于特定数。函数应该返回这两个数的下标,index1必须小于index2。注意返回的值是0-based。请使用双指针完成本题,否则你有可能会被取消比赛资格。注意事项:```- 数据保证nums中的所有数的互不相同的。- nums数组长度≤100000- nums内的数≤1000000000``…

LeetCode题解349.intersection-of-two-arrays

题目地址 https://leetcode.com/problems/intersection-of-two-arrays/description/ 题目描述 Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1…

LeetCode题解? 170. Two Sum III - Data Structure Design

Design and implement a TwoSum class. It should support the following operations: add and find.add - Add the number to an internal data structure.find - Find if there exists any pai…

LeetCode题解29.divide-two-integers

题目地址 https://leetcode.com/problems/divide-two-integers/description/ 题目描述 Given two integers dividend and divisor, divide two integers without using multiplication, division and mod…

LeetCode题解167.two-sum-ii-input-array-is-sorted

题目地址 https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/ 题目描述 这是leetcode头号题目two sum的第二个版本,难度简单。 Given an array of integers that is already sorted in ascendi…