将 javascript循环写入计算 出现的次数的最有效方法是什么?(作为从1到100计算会遇到的示例数字?
示例:
function numberOccurences(targetNumber, minNumber, maxNumber) {
var count = 0;
for (i = minNumber; i < maxNumber; i++) {
count = count + (i.toString().split(targetNumber).length - 1);
}
return count;
}
var result = numberOccurences(7,1,100);
答案 0 :(得分:4)
这样做可以不看实际数字。对不起,没有循环,但你确实要求效率。如果你真的想使用循环,请进行递归和迭代。
function digitOccurences(digit, min, max, base) {
if (typeof base != "number") base = 10;
return digitOccurencesPlus(digit, max, base, 1, 0) - digitOccurencesPlus(digit, min, base, 1, 0);
function digitOccurencesPlus(digit, N, base, pow, rest) {
if (N == 0) return 0;
var lastDigit = N%base,
prevDigits = (N-lastDigit)/base;
var occsInLastDigit = pow*(prevDigits+(lastDigit>digit));
var occsOfLastInRest = rest * (lastDigit==digit);
// console.log(prevDigits+" "+lastDigit, rest, occsInLastDigit, occsOfLastInRest);
return occsInLastDigit + occsOfLastInRest + digitOccurencesPlus(digit, prevDigits, base, pow*base, pow*lastDigit+rest);
}
}
答案 1 :(得分:1)
这是一个有趣的问题,并且已经有其他语言的类似答案。也许你可以尝试在javascript中创建这个:Count the number of Ks between 0 and N
该解决方案适用于从0到n的出现,但您可以轻松地使用它以这种方式从a到b进行计算:
occurences(a,b)= occurences(0,b)-occurences(0,a)
答案 2 :(得分:0)
这比原来的功能要快得多( x6 )...... JSPERF
function numberOccurences2(targetNumber, minNumber, maxNumber) {
var strMe = "";
for (i = minNumber; i < maxNumber; i++) {
strMe = strMe.concat(i);
}
var re = new RegExp(targetNumber,"g");
var num1 = strMe.length;
var num2 = strMe.replace(re, "").length;
num2 = num1- num2;
return (num2);
}
还有一种更快的方式......