oneby7

Bit Manipulation Counting and shifting bits

119. Sum of Two Integers

Medium

You are given two integers a and b. Return their sum, without using the operators + and - to add or subtract them.

Library calls that add for you, such as Python's sum, are ruled out too. The bit operators &, |, ^, ~, << and >> are allowed. A loop counter may count up as usual: the rule is about how a and b are added.

Example 1

Input: a = 13, b = 9

Output: 22

Explanation: In binary, 1101 plus 1001 is 10110, which is 22.

Example 2

Input: a = -7, b = 4

Output: -3

Explanation: Negative numbers are allowed, and so is a negative sum.

Example 3

Input: a = 1000000000, b = 1000000000

Output: 2000000000

Explanation: The largest possible sum. It still fits in a 32-bit int.

Check your understanding

Work out the answer for this input before you write any code.

a = 5, b = 3

Constraints

  • -109 ≤ a, b ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.