371. Sum of Two Integers

Share this post on:

Given two integers a and b, return the sum of the two integers without using the operators + and -.

Example 1:

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

Example 2:

Input: a = 2, b = 3
Output: 5

Constraints:

  • -1000 <= a, b <= 1000

许多死记硬背的点:

  1. 0xFFFFFFFF 是一个 十六进制 (0x) 数,表示 32位 中的所有位都为 1
  2. 负数的补码表示为:正数的二进制按位取反(~),再加 1
  3. a ^ MASK 是用来将高位变为 0,低 32 位保持原样。
  4. 超过 32 位整数最大值的数,在补码中是负数。转换方法:如果值超过 0x7FFFFFFF,可以用:~(a ^ MASK)
  5. a + b 可以表示为 a ^ b + (a & b) << 1

Share this post on:

Leave a Reply

Your email address will not be published. Required fields are marked *