如何用Dart实现ArrayAddition函数 对应JS代码的正确写法是什么
ArrayAddition函数的Dart语法实现
你需要的对应Dart代码如下,和提供的JS逻辑完全对齐:
String ArrayAddition(List<int> arr) { // 复制原数组避免修改传入的原始数据,不需要可删除该行直接操作arr List<int> tempArr = List.from(arr); tempArr.sort((a, b) => a - b); int maxNum = tempArr.removeLast(); int tot = 0; for (int i = 0; i < tempArr.length; i++) { tot += tempArr[i]; for (int j = 0; j < tempArr.length; j++) { if (i != j) { tot += tempArr[j]; if (tot == maxNum) { return "true"; } } } for (int k = 0; k < tempArr.length; k++) { if (i != k) { tot -= tempArr[k]; if (tot == maxNum) { return "true"; } } } tot = 0; } return "false"; }
调用示例
void main() { print(ArrayAddition([4, 6, 23, 10, 1, 3])); // 输出 true }
说明
- Dart中List的
removeLast()方法等价于JS数组的pop()方法 - 排序逻辑和JS保持一致,都是按数值升序排列
- 函数返回值为字符串类型的"true"/"false",符合需求要求
内容的提问来源于stack exchange,提问作者Mahmoud Al-Haroon
相关产品推荐
相关产品推荐

