MEDIUM NC#149 Blind #11 Bit Manipulation

371. Sum of Two Integers

๐Ÿ“– Problem

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

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Recursion reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Use XOR for addition without carry: a ^ b
  • โ†’ Use AND and left shift for carry: (a & b) << 1
  • โ†’ Repeat until there's no carry
  • โ†’ Time: O(1) - max 32 iterations for 32-bit integers, Space: O(1)

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse XOR for addition without carry: a ^ b
  • โ€ขUse AND and left shift for carry: (a & b) << 1
  • โ€ขRepeat until there's no carry

Common Pitfalls

  • โ€ขTime: O(1) - max 32 iterations for 32-bit integers, Space: O(1)

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
getSum(1, 2);
Expected:
3
Test Case 2
Not run
Input:
getSum(2, 3);
Expected:
5
Test Case 3
Not run
Input:
getSum(-1, 1);
Expected:
0

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit