JavaScript - 代码片段,Snippets,Gist
求n个数字的累加和
- 递归实现
function getSum(x) {
if (x == 1) {
return 1;
}
return x + getSum(x - 1);
}
var result = getSum(100);
console.log(result);
求一个数字的每个位数上的和 :如:23--->5
- 递归实现
function getnumberSum(x) {
if (x < 10) {
return x;
}
return parseInt(x % 10 + getnumberSum(x / 10));
}
console.log(getnumberSum(123));