leetcode/lcci/17.01.Add Without Plus
..
README.md
README_EN.md
Solution.java
Solution.swift

README_EN.md

comments difficulty edit_url
true Easy https://github.com/doocs/leetcode/edit/main/lcci/17.01.Add%20Without%20Plus/README_EN.md

17.01. Add Without Plus

中文文档

Description

Write a function that adds two numbers. You should not use + or any arithmetic operators.

Example:


Input: a = 1, b = 1

Output: 2

 

Note:

  • a and b may be 0 or negative.
  • The result fits in 32-bit integer.

Solutions

Solution 1

Java

class Solution {
    public int add(int a, int b) {
        int sum = 0, carry = 0;
        while (b != 0) {
            sum = a ^ b;
            carry = (a & b) << 1;
            a = sum;
            b = carry;
        }
        return a;
    }
}

Swift

class Solution {
    func add(_ a: Int, _ b: Int) -> Int {
        var a = a
        var b = b
        var sum = 0
        var carry = 0

        while b != 0 {
            sum = a ^ b
            carry = (a & b) << 1
            a = sum
            b = carry
        }

        return a
    }
}