练习题:打印出1-10000之间的所有对称数(如121,1331,2442)。
自己写的代码:
var isSym = function (num) { var str = ''; for (var i = 1; i <=9; i++) { //如果个位算,可去掉注释 //str+=i;str += ','; for (var j = 1; j <= 9; j++) { if (i == j) { str = str + i + ',' ; str = str + i + j + i + ','; } str = str + i + j+j + i + ','; } } return str; } isSym(10000);
结果:
别人写的代码:
1.
function test1(n){ var arr = []; for(var i = 1;i < n/10;i++){ i = i.toString(); arr.push(i[0]+ '' + i.split("").reverse().join("")); } return arr; } document.write(test1(10000));
2.
function judgeNum(start,end){ for(var i = start;i < end; i++){ var strI = i.toString().split("").reverse("").join(""); if(Number(strI) == i && i > 10){ console.log(strI); } } } judgeNum(1,10000);
3.
function getReverseNumber (num) { var result = []; for (var i = 10; i < num + 1; i++) { var a = i.toString(); var b = a.split("").reverse().join(""); if(a === b) {result.push(b);} }; return result; } getReverseNumber(10000);
4.
var n= function(){ var str = ""; var res = ""; for(var num = 0;num<=10000;num++){ str=num++; if(str.length>1 && str[0] == str[str.length-1]){ if(str.length<4){ res += str+'\n'; } if(str.length ==4){ if(str[1] == str[2]){ res += str +'\n'; } } } } return res; }
时间: 2024-11-08 23:57:29