我看到了question在 Leetcode 中。
另外,我在其中找到了解决方案。
我不明白的一件事是这行代码
while(n-- >1)
有人可以解释一下 --> 的含义吗? 这是 JS:
var countAndSay = function(n) {
var result = "1";
var prev;
var count;
var tmp;
while (n-- > 1) {
prev = result[0];
count = 1;
tmp = [];
for (var i = 1; i < result.length; i++) {
if (prev === result[i]) {
count++;
} else {
tmp.push(count, prev);
prev = result[i];
count = 1;
}
}
tmp.push(count, prev);
result = tmp.join("");
}
return result;
};
console.log(countAndSay(4))
最后一件事,有人可以解释一下这个问题的含义吗。
我还是不明白为什么2是11,3是21,4是1211,5是111221。
最佳答案
表达式
n-- > 1
意思是:将n
减一,并检查其减前的值是否大于1。
while (n-- > 1) {
// rest of the code
相当于
while (true) {
if (n > 1) {
n--;
// rest of the code
} else {
// n is decremented regardless:
n--;
// initial condition was not fulfilled:
break;
}
或者,条件是否定:
while (true) {
const origN = n;
n--;
if (!(origN > 1)) {
break;
}
// rest of the code
关于javascript - while(n- ->1) 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55253620/