文章目录
codewars-js练习
2021/3/5
github 地址
【1】<7kyu>【Convert an array of strings to array of numbers】
example:
["1", "2", "3"] //[1, 2, 3]
["1.1","2.2","3.3"]// [1.1,2.2,3.3]
solution
<script type="text/javascript">
function toNumberArray(stringarray){
// console.log(stringarray)
var result = [];
for(var i=0;i<stringarray.length;i++){
if(stringarray[i]%1 ==0){
result.push(parseInt(stringarray[i]))
}else{
result.push(parseFloat(stringarray[i]))
}
}
return result
}
// 验证
console.log(toNumberArray(["1.1","2.2","3.3"]));// [1.1,2.2,3.3]
console.log(toNumberArray(['1','2','3']))
</script>
【2】<7kyu>【Nth Root of a Number】
example:
Input: x=4, n=2, output: 2. The square root of 4 is 2, 2^2 = 4
Input: x=8, n=3, output: 2. The cube root of 8 is 2 , 2^3 = 8
Input: x=256, n=4, output: 4. The 4th root of 256 is 4 , 4^4 = 256
Input: x=9, n=2, output: 3. The square root of 9 is 3 , 3^2 = 9
Input: x=6.25, n=2, output: 2.5. The square root of 6.25 is 2.5 , 2.5^2 = 6.25
solution
<script type="text/javascript">
function root(x,n) {
// console.log(x,n)
return Math.pow(x, 1/n)
}
// 验证
console.log(root(4,2));//2
console.log(root(256,4));//4
</script>
【3】<6kyu>【Roman Numerals Decoder】
So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
example:
solution('XXI'); // should return 21
solution
<script type="text/javascript">
function solution(roman){
console.log(roman)
var value = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000};
var arr = roman.split('');
var sum =0;
for(var i=0;i<arr.length;i++){
if (i>0 && value[arr[i]]>value[arr[i-1]]){
sum = sum - 2*value[arr[i-1]]
}
sum += value[arr[i]];
}
return sum
}
// 验证
// console.log(solution('XXI'));//21
// console.log(solution('I'));//1
console.log(solution('IV'));// 4
// console.log(solution('MMVIII'));//2008
// console.log(solution('MDCLXVI'));//1666
</script>
以上为自己思路供大家参考,可能有更优的思路。
本文分享了三道Codewars JavaScript练习题的解答思路与实现代码:字符串数组转数值数组、求N次方根及罗马数字转换为十进制数。适合初学者参考学习。

被折叠的 条评论
为什么被折叠?



