LeetCode 2695: Array Wrapper

Problem Description

Explanation

To solve this problem, we will create a class ArrayWrapper with two overloaded operators: + for adding two instances of the class and String() for converting the array to a string format. We will implement the addition by summing up the elements of the arrays and the String() function by returning a comma-separated string surrounded by brackets.

Solutions

class ArrayWrapper {
    private int[] nums;

    public ArrayWrapper(int[] nums) {
        this.nums = nums;
    }

    public int sum() {
        int total = 0;
        for (int num : nums) {
            total += num;
        }
        return total;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < nums.length; i++) {
            sb.append(nums[i]);
            if (i < nums.length - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }

    public static ArrayWrapper add(ArrayWrapper a, ArrayWrapper b) {
        int[] result = new int[a.nums.length + b.nums.length];
        System.arraycopy(a.nums, 0, result, 0, a.nums.length);
        System.arraycopy(b.nums, 0, result, a.nums.length, b.nums.length);
        return new ArrayWrapper(result);
    }
}

Loading editor...