gpt4 book ai didi

Javascript 循环性能 : Counting occurrences of a number in a finite series

转载 作者:行者123 更新时间:2023-11-30 08:43:54 25 4
gpt4 key购买 nike

编写 javascript 循环计算 7 的出现次数 的最有效方法是什么(作为示例数字) 从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);

最佳答案

这将在不查看实际数字的情况下完成。对不起,没有循环,但你确实要求效率。如果你真的想使用循环,进行递归和迭代。

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);
}
}

关于Javascript 循环性能 : Counting occurrences of a number in a finite series,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23689757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com