列表

详情


2695. 包装数组

创建一个名为 ArrayWrapper 的类,它在其构造函数中接受一个整数数组作为参数。该类应具有以下两个特性:

 

示例 1:

输入:nums = [[1,2],[3,4]], operation = "Add"
输出:10
解释:
const obj1 = new ArrayWrapper([1,2]);
const obj2 = new ArrayWrapper([3,4]);
obj1 + obj2; // 10

示例 2:

输入:nums = [[23,98,42,70]], operation = "String"
输出:"[23,98,42,70]"
解释:
const obj = new ArrayWrapper([23,98,42,70]);
String(obj); // "[23,98,42,70]"

示例 3:

输入:nums = [[],[]], operation = "Add"
输出:0
解释:
const obj1 = new ArrayWrapper([]);
const obj2 = new ArrayWrapper([]);
obj1 + obj2; // 0

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
/** * @param {number[]} nums */ var ArrayWrapper = function(nums) { }; ArrayWrapper.prototype.valueOf = function() { } ArrayWrapper.prototype.toString = function() { } /** * const obj1 = new ArrayWrapper([1,2]); * const obj2 = new ArrayWrapper([3,4]); * obj1 + obj2; // 10 * String(obj1); // "[1,2]" * String(obj2); // "[3,4]" */

typescript 解法, 执行用时: 60 ms, 内存消耗: 44.2 MB, 提交时间: 2023-05-22 14:23:57

class ArrayWrapper {
    private _nums: number[]
    
	constructor(nums: number[]) {
        this._nums = nums
    }

	valueOf() {
        return this._nums.reduce((sum, cur) => sum + cur, 0)
    }

	toString() {
        return `[${this._nums}]`;
    }
};

/**
 * const obj1 = new ArrayWrapper([1,2]);
 * const obj2 = new ArrayWrapper([3,4]);
 * obj1 + obj2; // 10
 * String(obj1); // "[1,2]"
 * String(obj2); // "[3,4]"
 */

javascript 解法, 执行用时: 48 ms, 内存消耗: 41.3 MB, 提交时间: 2023-05-22 14:23:39

/**
 * @param {number[]} nums
 */
var ArrayWrapper = function (nums) {
    this.values = nums
};

ArrayWrapper.prototype.valueOf = function () {
    return this.values.reduce((pre, cur) => pre + cur, 0)
}

ArrayWrapper.prototype.toString = function () {
    return '[' + this.values + ']'
}

/**
 * const obj1 = new ArrayWrapper([1,2]);
 * const obj2 = new ArrayWrapper([3,4]);
 * obj1 + obj2; // 10
 * String(obj1); // "[1,2]"
 * String(obj2); // "[3,4]"
 */

javascript 解法, 执行用时: 68 ms, 内存消耗: 41.7 MB, 提交时间: 2023-05-22 14:23:16

/**
 * @param {number[]} nums
 */
var ArrayWrapper = function(nums) {
    this.a = nums
};

ArrayWrapper.prototype.valueOf = function() {
    return this.a.reduce((a,b) => a + b, 0)   
}

ArrayWrapper.prototype.toString = function() {
    return `[${this.a.join()}]`
}

/**
 * const obj1 = new ArrayWrapper([1,2]);
 * const obj2 = new ArrayWrapper([3,4]);
 * obj1 + obj2; // 10
 * String(obj1); // "[1,2]"
 * String(obj2); // "[3,4]"
 */

上一题