Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Sum Two Numbers Without + or sum

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Sum Two Numbers Without + or sum. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Reply data-processing code may need a low-level integer operation that does not rely on Python's arithmetic addition. Implement a function that adds two signed integers without using the + operator, sum(), .sum(), operator.add, or equivalent arithmetic helpers.

Formal Specification

Implement add_integers(a, b):

  • Input: Two Python integers a and b in the signed 32-bit range.
  • Output: Their mathematical sum as a Python integer.
  • Use bitwise operations such as XOR, AND, left shift, and masking to simulate binary addition.
  • The implementation must correctly handle positive values, negative values, zero, and sums outside the signed 32-bit range.
  • Do not convert the integers to strings or lists of bits.

Python integers use unlimited precision and conceptually extend negative values with infinite leading ones. Explain how your implementation uses a fixed-width two's-complement representation to ensure termination and then converts the result back to a Python integer.

Constraints

  • -2^31 <= a, b <= 2^31 - 1
  • The output must be the exact mathematical sum.
  • The + operator, sum(), .sum(), and arithmetic addition helpers are prohibited.
  • String conversion and conversion to a list of bits are prohibited.

Function Signature

def add_integers(a, b):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output