Blind 75

Sum of Two Integers

Problem
LC 371
Category
Binary
File
blind75_LC371SumOfTwoIntegers.java
Path
pkg5leetcode/blind75/blind75_LC371SumOfTwoIntegers.java
Package
pkg5leetcode.blind75
Command
java pkg5leetcode/blind75/blind75_LC371SumOfTwoIntegers.java
Approach
Bit manipulation XOR for sum, AND<<1 for carry until no carry.
Complexity
Time O(1), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/blind75/blind75_LC371SumOfTwoIntegers.java
1package pkg5leetcode.blind75;2 3/*4 * Sum of Two Integers | LC 3715 * APPROACH: Bit manipulation XOR for sum, AND<<1 for carry until no carry.6 * COMPLEXITY: Time O(1), Space O(1)7 */8public class blind75_LC371SumOfTwoIntegers {9    static int getSum(int a, int b) {10        while (b != 0) {11            int carry = (a & b) << 1;12            a = a ^ b;13            b = carry;14        }15        return a;16    }17 18    public static void main(String[] args) {19        check(getSum(1, 2) == 3, "case1");20        check(getSum(2, 3) == 5, "case2");21        System.out.println("all tests passed");22    }23 24    static void check(boolean cond, String name) {25        if (!cond) throw new AssertionError("FAILED: " + name);26        System.out.println("  PASS " + name);27    }28}