algoadvance

Leetcode 2235. Add Two Integers

Problem Statement:

You are given two integers num1 and num2 representing two integers. Implement a function that returns the sum of num1 and num2.

Example:

Input: num1 = 12, num2 = 5
Output: 17
Input: num1 = -10, num2 = 4
Output: -6

Clarifying Questions:

  1. Are num1 and num2 guaranteed to be non-null?
    • Yes, both integers are always provided and valid.
  2. Can num1 and num2 be negative?
    • Yes, they can be negative.
  3. What is the range of num1 and num2?
    • They are within the range of a typical 32-bit signed integer.

Strategy:

The problem is straightforward. The task is to return the sum of the two integers. This can be achieved by simply using the + operator in Java.

Code:

public class Solution {
    public int sum(int num1, int num2) {
        return num1 + num2;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.sum(12, 5)); // Output: 17
        System.out.println(solution.sum(-10, 4)); // Output: -6
    }
}

Time Complexity:

The time complexity for this function is O(1) because adding two integers is a constant time operation.

Space Complexity:

The space complexity is O(1) since no extra space is used beyond the input integers and the output value.

If you have any further questions or need additional examples, feel free to ask!

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI