gpt4 book ai didi

javascript - JS : Repeated string (Hackerrank Challenge)

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:28:18 24 4
gpt4 key购买 nike

我正在做 Hackerrank 中的一项挑战,如下所示:

Lilah has a string, s, of lowercase English letters that she repeated infinitely many times.

Given an integer, n, find and print the number of letter a’s in the first n letters of Lilah’s infinite string. The first line contains a single string, s. The second line contains an integer, n.

我需要打印一个整数,表示通过无限次重复 S 创建的无限字符串的前 N ​​个字母中字母 a 的数量。

例如:

s is 'aba', n = 10.. The first n = 10 letters of the infinite string are 'abaabaabaa...' Because there are 7 a’s, we'll get 7 as the final answer

这是我的答案。它通过了前两个案例,但未通过其余案例。

function repeatedString(s, n) {
var repeat = Math.round(n / s.length);
var remainder = n % s.length;
var answer = 0;
for (var i = 0; i < s.length; i++) {
if (s.charAt(i) == 'a') {
answer += repeat;
if (i < remainder)
answer++;
}
}
return answer;
}

如果有人可以看看这个并提出更好的解决方案,那就太好了。

最佳答案

//From a website i found it.

const as = s.split("").filter(c => c === "a").length;
const times = parseInt(n / s.length);
const rest = n % s.length;

const totalAs = times * as
+ s.slice(0, rest).split("").filter(c => c === "a").length

return totalAs;

关于javascript - JS : Repeated string (Hackerrank Challenge),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53509604/

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