js数据结构与算法--递归
递归,函数自己调用自己
return
- 返回值,
- 后面的代码不执行
function fn(num){ console.log(num) if(num == 0){ return; } fn(num-1) } fn(10)
1-100之间,把所有能被3并且能被5整除的数获到,然后累加求和
for循环
function fn(num) { var sum = 0; for (var i = 0; i < num; i++) { if (i % 3 == 0 && i % 5 == 0) { sum += i; } } return sum; } console.log(fn(100))
递归
function fn(num) { if (num > 100) { return 0; } if (num % 15 == 0) { return num + fn(num + 1) } return fn(num + 1) } console.log(fn(1)); // 1 -> fn(1+1) // 2 -> fn(2+1) // ... //15 -> 15+fn(15+1) // 16 -> 15+fn(16+1) // 30 -> 15+fn(30+1); // 31 -> 15+30+fn(31+1) // ... // 15+30+45+60+75+90+fn(100) // 15+30+45+60+75+90+fn(101) => 15+30+45+60+75+90+0
1-10之间,把所有能被2整除的数获到,然后累加求和
function fn(num) { if (num > 10) { return 0; } if (num % 2 == 0) { return num + fn(num + 1) } return fn(num + 1) } console.log(fn(1)); // 1 => fn(1+1) => fn(2) // 2 => 2+fn(2+1) => 2+fn(3) // 3 => 2+fn(3+1) => 2+fn(4) // 4 => 2+4+fn(4+1) => 2+4+fn(5) //.. //10 2+4+6+8+10+fn(11) //11 2+4+6+8+10+0
1-10以内所有偶数积
function fn(num){ if(num<1){ return 1; } if(num%2 ==0){ return num* fn(num-1) } return fn(num-1) } var result = fn(10); console.log(result);
相关推荐
哈嘿Blog 2020-10-26
明月清风精进不止 2020-07-05
PythonMaker 2020-07-05
xirongxudlut 2020-06-28
kkpiece 2020-06-16
qscool 2020-06-12
CloudXli 2020-06-11
vs00ASPNET 2020-06-09
Dimples 2020-06-08
kuoying 2020-06-07
JJandYY 2020-05-31
Wyt00 2020-05-30
liuyh 2020-04-03
CloudXli 2020-05-11
世樹 2020-05-11
bizercsdn 2020-05-10
joyjoy0 2020-05-09