-
-
Notifications
You must be signed in to change notification settings - Fork 241
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
使用递归完成 1 到 100 的累加 #138
Comments
function sum(num){
if(num === 1) return 1
return num + sum(num - 1);
}
console.log(sum(100)); |
尾递归优化,一行代码解决 function process(cur, total = 0) {
return cur === 0 ? total : process(cur - 1, total + cur);
} |
function accumulate(curr, max, total = 0) {
return curr > max ? total : accumulate(curr + 1, max, total + curr);
}
console.log(accumulate(1,100)); // 5050 |
// 直接就是一个循环
const sum = (min, max) => {
let total = 0
while(min <= max) {
total += min
min+=1
}
return total
}
// 递归: 相当于 min + (min + 1) + (min + 1 + 1)……
const sum1 = (min, max) => {
if (min === max) return min
return min + sum1(min + 1, max)
} |
function recursionNum(max = 0, total = 0) {
return max === 0 ? total : recursionNum(max - 1, total + max)
} |
function process(cur, sum = 0) {
return cur === 0 ? sum : process(cur - 1, sum + cur);
}
console.log(process(100)); |
function f(n){ |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: