1. 計算1到N總和(1 + 2 + 3 +...+N)
遞迴解法
function sum(n){
if(n<1){
return n
}
return n + sum(n-1);
}
var total = sum(10);
console.log("total:" + total);
迴圈版本
function sumByFor(n){
var total = 0;
for(i=1;i<=n;i++){
total+=i
}
return total;
}
var total = sumByFor(10);
console.log("total by for loop:" + total);
2. 1*2+2*3+...+(n-1)*n
遞迴解法
function sumContinue(n){
if(n<2){
return 0
}
return n*(n-1) + sumContinue(n-1);
}
var total = sumContinue(10);
console.log("total continue:" + total);
迴圈解法
function sumContinueByFor(n){
var total =0;
for(i=2;i<=n;i++){
total +=i*(i-1);
}
return total;
}
var total = sumContinueByFor(10);
console.log("sumContinue by for loop:" + total);
3.不使用暫存變數交換兩個變數 ( Swap two variables without using a temporary variable )
XOR交換方式
a =3;
b = 4;
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log("a:"+ a + " b:"+b);
4.從陣列中找出缺少的數字
const findMissing = (data) => {
let max = data[0]
let min = data[0]
let sum = 0;
for (i = 0; i < data.length; i++) {
let n = data[i];
min = (data[i]>min) ? min :data[i]
max = (data[i]>max) ? data[i]: max
sum+= n;
}
return (max+min)* (max - min + 1) /2 - sum;
};
let value = findMissing([3,4,6,7,8,9])
console.log("missing value: "+ value)
5.單迴圈做出99乘法表
let i = 9;
let j = i;
while(i>0){
console.log(i+"*"+j + "="+ i*j)
j--;
if(j<1){
i--;
j=9;
}
}