简体   繁体   English

为什么在评估所有内容之前我的for循环停止?

[英]Why is my for loop stopping before everything is evaluated?

I'm trying to get the largest palindrome made from the product of two 3-digit numbers. 我正在尝试从两个3位数的乘积中得到最大的回文。 In case you don't know, a palindrome is a number that is the same forwards as it is backward (ex: 9009, or 55855, etc..). 如果您不知道,回文数就是向前和向后相同的数字(例如:9009或55855等)。

My method involves looping through all three digit numbers and multiplying them, if the product matches itself reversed, updating the variable 'palindrome' with that product. 我的方法涉及遍历所有三个数字,如果乘积本身反转,则将它们相乘,然后用该乘积更新变量“回文”。 I'm expecting 906609, but it's returning 99999. 我期望906609,但它返回99999。

Been racking my brain on this one, don't see anything wrong but there's obviously something. 我一直在脑海中思考这个问题,没有发现任何错误,但显然有什么问题。 Any thoughts? 有什么想法吗?

//Hoist 'palindrome'
var palindrome = 0;

//Loop through 100 - 1000
for(var i = 100; i < 1000; i++) {

    //Within that loop, loop through 100 - 1000
    for(var k = 100; k < 1000; k++) {

        //Convert product of K & I and reverse to strings
        var product = (k * i).toString(); 
        var reversed = product.match(/.{1}/g).reverse().toString().replace(/,/g, '');

        //If the product and reverse are the same, update palindrome
        if(product === reversed) {
            if(reversed > palindrome) {
                var palindrome = product;
            }
        }
    }
}

//Expecting 906609, but returns 99999
console.log(palindrome)

because 因为

 "99999" > "906609" // true

as you are comparing strings, they are compared lexically. 当您比较字符串时,将按词法比较它们。 You want to compare numbers: 您要比较数字:

 if(+reversed > +palindrome)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM