LeetCode //2695. Array Wrapper (Day 28 of LC JavaScript Challenage)

文章描述了一个ArrayWrapper类的设计,该类在构造时接受一个整数数组。类有两个主要功能:当两个实例使用加号操作符相加时,结果是两个数组元素之和;调用toString方法时,返回数组元素以逗号分隔并由方括号包围的字符串表示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2695. Array Wrapper

Create a class ArrayWrapper that accepts an array of integers in it’s constructor. This class should have two features:

  • When two instances of this class are added together with the + operator, the resulting value is the sum of all the elements in both arrays.

  • When the String() function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3].

 

Example 1:

Input: nums = [[1,2],[3,4]], operation = “Add”
Output: 10
Explanation:
const obj1 = new ArrayWrapper([1,2]);
const obj2 = new ArrayWrapper([3,4]);
obj1 + obj2; // 10

Example 2:

Input: nums = [[23,98,42,70]], operation = “String”
Output: “[23,98,42,70]”
Explanation:
const obj = new ArrayWrapper([23,98,42,70]);
String(obj); // “[23,98,42,70]”

Example 3:

Input: nums = [[],[]], operation = “Add”
Output: 0
Explanation:
const obj1 = new ArrayWrapper([]);
const obj2 = new ArrayWrapper([]);
obj1 + obj2; // 0

Constraints:
  • 0 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • Note: nums is the array passed to the constructor

From: LeetCode
Link: 2695. Array Wrapper


Solution:

Ideas:
The idea behind this code is to create a class that can wrap an array of numbers and provide two useful methods: valueOf and toString. The valueOf method will add all of the numbers in the array together and return the sum, while the toString method will create a string representation of the array by separating each number with a comma and enclosing the entire list in square brackets.
Code:
/**
 * @param {number[]} nums
 */
var ArrayWrapper = function(nums) {
    this.nums = nums;
};

ArrayWrapper.prototype.valueOf = function() {
    var sum = 0;
    for (var i = 0; i < this.nums.length; i++) {
        sum += this.nums[i];
    }
    return sum;
}

ArrayWrapper.prototype.toString = function() {
    var str = "[";
    for (var i = 0; i < this.nums.length; i++) {
        if (i > 0) {
            str += ",";
        }
        str += this.nums[i];
    }
    str += "]";
    return str;
}

/**
 * const obj1 = new ArrayWrapper([1,2]);
 * const obj2 = new ArrayWrapper([3,4]);
 * obj1 + obj2; // 10
 * String(obj1); // "[1,2]"
 * String(obj2); // "[3,4]"
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值