内容中心

2026年靠谱的网关联网储物柜智能柜锁精选公司-宁波望通锁业有限公司

To solve this problem, we need to find the sum of two integers without using the standard arithmetic operators + or -. Instead, we leverage bitwise operations to simulate addition, as binary addition can be broken down into bitwise XOR (for sum without carry) and bitwise AND (for carry).

Approach

The key insight here is understanding how binary addition works:

  1. XOR Operation: The XOR (^) of two bits gives the sum of the bits without considering the carry. For example, 1 ^ 1 = 0 (sum without carry), 1 ^ 0 = 1, etc.
  2. AND Operation: The AND (&) of two bits gives the carry. For example, 1 & 1 = 1 (carry), 1 & 0 = 0, etc. The carry needs to be shifted left by one position (<< 1) to align with the next higher bit.

For negative numbers, we use a 32-bit mask (0xFFFFFFFF) to simulate fixed-size integers (since Python uses arbitrary-length integers). After processing, we convert the result back to a Python integer if it's a negative number (by checking if it exceeds the maximum 32-bit positive integer 0x7FFFFFFF).

Solution Code

def add(a: int, b: int) -> int:
    mask = 0xFFFFFFFF
    max_int = 0x7FFFFFFF

    while b != 0:
        # Compute sum without carry and carry with shift
        a, b = (a ^ b) & mask, ((a & b) << 1) & mask

    # Convert to Python's negative integer if needed
    return a if a <= max_int else ~(a ^ mask)

Explanation

  1. Loop Until Carry is Zero: We keep updating the sum (a) and carry (b) until the carry becomes zero. This ensures all carry values are added back to the sum.
  2. Mask Handling: The mask 0xFFFFFFFF ensures we work within 32-bit integers, preventing infinite loops for negative numbers.
  3. Negative Number Conversion: If the result (a) exceeds the maximum 32-bit positive integer (0x7FFFFFFF), it means the result is a negative number. We convert it back to a Python integer using ~(a ^ mask), which gives the correct negative value.

This approach efficiently computes the sum using bitwise operations, handling both positive and negative integers correctly. The time complexity is O(1) (since we process at most 32 bits) and space complexity is O(1).

Example:

  • For a = 3 and b =5, the code returns 8 (correct sum).
  • For a = -1 and b =1, the code returns 0 (correct sum).
  • For a = 1 and b =-2, the code returns -1 (correct sum).

This solution is optimal and works for all valid integer inputs.

宁波望通锁业有限公司

宁波望通锁业有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?