GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/problems/371.sum-of-two-integers.md at master · zfcfuture/leetcode

Expand file tree

/

371.sum-of-two-integers.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
61 lines (41 loc) · 1.31 KB
/

371.sum-of-two-integers.md

Copy path

File metadata and controls

61 lines (41 loc) · 1.31 KB
Raw
Copy raw file
Download raw file
Outline
Edit and raw actions

题目地址

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,因此我们可以把异或看成是一种不进位的加减法。

371.sum-of-two-integers-1

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

371.sum-of-two-integers-2

然后我们对上述两个元算结果递归求解即可。 递归的结束条件就是其中一个为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);
};
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.