codewars-js练习
2021/2/7
github 地址
【1】<5kyu>【Common Denominators】
example:
convertFracs [(1, 2), (1, 3), (1, 4)] `shouldBe` [(6, 12), (4, 12), (3, 12)]
solution
<script type="text/javascript">
function convertFrac(lst){
var gcd = (a, b) => b ? gcd(b, a % b) : a;
var lcm = lst.reduce((res, i) => res * i[1] / gcd(res, i[1]), 1);
return lst.reduce((res, i) => res + '('+ lcm / i[1] * i[0] +','+ lcm +')', '');
}
// 验证
var lst = [ [1, 2], [1, 3], [1, 4] ]
console.log(convertFrac(lst));//'(6,12)(4,12)(3,12)'
</script>
【2】<6kyu>【Find the odd int】
Given an array of integers, find the one that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
给定一个整数数组,找出出现奇数次的整数。
example:
[20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]// 5
[1,1,2,-2,5,2,4,4,-1,-2,5]// -1
[10], 10
[5,4,3,2,1,5,4,3,2,10,10], 1
solution
<script type="text/javascript">
function findOdd(A) {
// 总思路:统计每个数出现的次数,并且记住索引
// console.log(A);
var map = {};
for(var i=0;i<A.length;i++){
// 获取到每个元素
var key = A[i];
// console.log('key',key);
// 通过判断新对象中是否含有,则来判断每个数出现的次数
if(map[key]){
map[key] ++;
}else{
map[key] =1;
}
}
// console.log('map:',map);
// 遍历对象
for(var key in map){
// console.log(map[key]);
if(map[key] %2 !=0){
return parseInt(key);
}
}
}
// 验证
console.log(findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]));// 5
console.log(findOdd([10]));//10
</script>
以上为自己思路供大家参考,可能有更优的思路。