java - 如果相同,则将数组中的值相乘
问题描述
我想写一个遵循这个逻辑的递归方法:
假设如果数组是 [3, 3, 3, 3] 它将返回值 30,因为 trail[i] 的连续数字彼此相等。所以这里发生的是 3 + (3 * 2) + (3 * 3) + (3 * 4) = 30
另一个例子是 [2, 4, 3] 它将返回值 9
我希望这是有道理的
任何人都可以帮忙吗?
解决方案
你可以试试这个方法
int sum(int pos, int[] trail, int cnt) {
if (pos >= trail.length) { // when full array traversed
return 0;
}
if (pos != 0 && trail[pos - 1] == trail[pos]) { // if previous element is same
return (cnt + 1) * trail[pos] + sum(pos + 1, trail, cnt + 1);
} else { // first element or prev not same
return trail[pos] + sum(pos + 1, trail, 1);
}
}
并以这种方式调用sum(0, trail, 0)
推荐阅读
- windows - 跨路由器的 Windows 网络文件夹
- regex - R中非常大的文件的字符串匹配
- css - 在 vue2JS 中从上滑动全屏 div
- angular - 角度:通过两个 ngFors 更新指定 dom 的一部分
- amazon-web-services - AWS ec2 实例标签名称 Powershell
- sql-server - 查找两个日期期间之间的重叠天数
- css - 如何在 CSS 中将 hr 线旋转 90 度并在其前面放置文本?
- email - Drupal 无法主题密码重置邮件
- python - gTTS 不保存 MP3 文件
- android - 如何在 Oreo(API 级别 28)中运行连续的周期性后台工作(以 15 分钟的周期间隔),甚至在打瞌睡模式下运行?