java - 简单递归到迭代
问题描述
我认为我的解决方案太复杂了,我该如何简化它?
问题:
public static int calc (int g, int h) {
if (h > 5) {
g += h;
return calc (g, h − 2) ∗ 2;
} else {
return g;
}
}
我的解决方案:
public static int calc (int g, int h) {
int counter = 0;
for (; h > 5; h -= 2){
g += h;
counter++;
}
return g * (int) Math.pow(2, counter);
}
解决方案
I'd be more inclined to simplify your original recursive code:
public static int calc(int g, int h) {
if (h <= 5) {
return g;
}
return 2 * calc(g + h, h - 2);
}
But if I were to simplify your iterative code, I'd try to avoid introducing the floating point Math.pow()
and keep the whole operation int
:
public static int calc(int g, int h) {
int power;
for (power = 1; h > 5; h -= 2) {
g += h;
power *= 2;
}
return g * power;
}
推荐阅读
- mysql - 如何对 MySQL 数据库执行复杂的更新?
- sql - 已解决 - 为什么尝试仅更新一列时列值变为 NULL?
- apache-spark - Spark-submit with Stocator failed with Class com.ibm.stocator.fs.ObjectStoreFileSystem not found 错误
- angular - tslint import 已声明,但其值永远不会被误读为误报
- javascript - React Router:传递给其包装器的奇怪匹配的 Route 路径道具
- android - 在谷歌播放中上传后应用程序的意外行为导致崩溃
- python - 如何检测关闭的 PyQt 对话框
- java - 如何在两个线程中打印句子?
- angular - 为什么在我的 http 拦截器的 Jasmine 单元测试中出现错误:超时?
- javascript - 带有线条的 Fusioncharts 区域范围图