You need to enable JavaScript to run this app. 如何用Dart实现ArrayAddition函数 对应JS代码的正确写法是什么
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 04:27:04