日期:2014-05-16 浏览次数:20397 次
第一种办法是运行正则表达式来实现的,如下列代码中的:markReg方法。这个方法可以判断n位数水仙花查找。只要指定option参数就行。
第二种办法是正常的方法来实现。如下列代码中的:markDemo方法。这个方法只实现3位数的水仙花查找。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>寻找水仙花-两种方法</title> <script type="text/javascript" src="自己测试/jquery-ui/js/jquery-1.4.2.min.js"></script> <script type="text/javascript"> function Sxh(){ this.value = 100; this.reg = /(\d)(\d)(\d)/; this.num = 3; this.markReg = function(){ var str=''; this.reg.exec(this.value); for(var j=1;j<this.num;j++){ str += "Math.pow(RegExp.$"+j+","+this.num+")+"; } str += "Math.pow(RegExp.$"+this.num+","+this.num+")"; if(eval(str) == this.value){return true;}else{return false;} } this.set = function(option){ this.value = option.value; this.num = option.num; this.reg = option.reg; } this.markDemo = function(){ var a = Math.floor(this.value / 100); var b = Math.floor(this.value % 100 / 10); var c = Math.floor(this.value % 100 %10); var v = Math.pow(a,3)+Math.pow(b,3)+Math.pow(c,3); if(v == this.value){return true;}else{return false;} } } $(function(){ var s = new Sxh(); for(var j = 100; j<1000;j++){ s.value = j; if(s.markReg()){ $("#text").html($("#text").html()+" "+s.value); } if(s.markDemo()){ $("#text").html($("#text").html()+" "+s.value); } } }); function shui(i,reg,n){ var str=''; reg.exec(i); for(var j=1;j<n;j++){ str += "Math.pow(RegExp.$"+j+","+n+")+"; } str += "Math.pow(RegExp.$"+j+","+n+")"; return eval(str); } </script> </head> <body> <div id="text"> </div> </body> </html> ?