文章目录
-
- codewars-js练习
-
- 2021/1/19
-
- github 地址
- 【1】Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.==(即求1到num的和)==
- 【2】In this kata, you are asked to square every digit of a number and concatenate them.==(即每位数字分别平方最后连接返回)==
- 【3】Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.==(即,将两数相加,然后二进制形式返回和)==
- 【4】Very simple, given a number, find its opposite.==(即 取反)==
- 【5】Given an array of ones and zeroes, convert the equivalent binary value to an integer.==(即 将二进制转换成十进制)==
- 【6】Complete the square sum function so that it squares each number passed into it and then sums the results together.==(即 将数组中每位数字求平方相加)==
- 【7】Given: an array containing hashes of names.Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.
- 【8】You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.==(如果单词的长度是奇数,则返回中间的字符。如果单词的长度是偶数,则返回中间的2个字符。)==
- 【9】There is an array with some numbers. All numbers are equal except for one.==(即 找出数组中唯一一个不同的数字)==
- 【10】 For simplicity, you'll have to capitalize each word, check out how contractions are expected to be in the example below.==(即 将每个单词首字母大写)==
- 【11】Given two arrays `a` and `b` write a function `comp(a, b)` (`compSame(a, b)` in Clojure) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in `b` are the elements in `a` squared, regardless of the order.==(即 检查这两个数组是否具有“相同”的元素和相同的多重性。"相同"的意思是,在这里,b中的元素是a的平方中的元素,无论顺序如何。)==
- 【12】Given an array of integers, remove the smallest value. Do not mutate the original array/list. If there are multiple elements with the same value, remove the one with a lower index. If you get an empty array/list, return an empty array/list.Don't change the order of the elements that are left.**==(即 给定一个整数数组,**删除最小的值**。不要改变原来的数组/列表。如果有**多个具有相同值的元素**,则**删除下标较低**的元素。如果你得到一个空数组/列表,返回一个空数组/列表。不要改变剩下元素的顺序。)==
codewars-js练习
2021/1/19
github 地址
【1】Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.(即求1到num的和)
example:
summation(1);//1
summation(8);//36
solution:
<script type="text/javascript">
var summation = function (num) {
var sum = 0;
for(var i=0;i<=num;i++){
sum +=i;
}
return sum;
}
// 验证
console.log(summation(1));//1
console.log(summation(8));//36
</script>
【2】In this kata, you are asked to square every digit of a number and concatenate them.(即每位数字分别平方最后连接返回)
example:
For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
squareDigits(9119)//811181
思路:
- 将number先转换成str,再转换成数组;
- 获取数组每个数字进行平方;
- 将数组转为str,进行连接,最后转换成number进行返回
solution:
<script type="text/javascript">
function squareDigits(num){
// 将number转换成string类型
var str = num.toString();
// 进行切割转换为数组
var arr = str.split('');
var newArr = [];
// console.log(arr);
// 对每位数字进行平方操作
for(var i=0;i<arr.length;i++){
newArr.push(Math.pow(arr[i],2));
// console.log(newArr);
}
// 将得到的进行拼接
var newStr = newArr.join('');
// 转换成number,返回
var result = Number(newStr);
// console.log(result);
return result;
}
// 验证
console.log(squareDigits(9119));//811181
</script>
【3】Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.(即,将两数相加,然后二进制形式返回和)
example:
addBinary(1,2)//11
思路:
- 将十进制转为二进制
solution:
<script type="text/javascript">
function addBinary(a,b) {
var sum = a + b;
// 将十进制转换成二进制
return sum.toString(2);
}
// 验证
console.log(addBinary(1,2));//11
console.log(addBinary(0,1));//1
</script>
js进制转换总结:
-
十进制转换成二进制
num.toString(2)
-
二进制转换成十进制
parseInt(num,2)
-
八进制转十进制
parseInt(num,8)
-
十六进制转十进制
parseInt(num,16)
-
十进制转八进制
parseInt(num).toString(8)
-
十进制转十六进制
parseInt(num).toString(16)
-
二进制转八进制
parseInt(num,2).toString(8)
-
二进制转十六进制
parseInt(num,2).toString(16)
-
八进制转二进制
parseInt(num,8).toString(2)
-
八进制转十六进制
parseInt(num,8).toString(16)
-
十六进制转二进制
parseInt(num,16).toString(2)
-
十六进制转八进制
parseInt(num,16).toString(8)
【4】Very simple, given a number, find its opposite.(即 取反)
example:
1: -1
14: -14
-34: 34
solution:
<script type="text/javascript">
function opposite(number) {
return (-number);
}
// 验证
console.log(opposite(1));//-1
console.log(opposite(14));//-14
</script>
【5】Given an array of ones and zeroes, convert the equivalent binary value to an integer.(即 将二进制转换成十进制)
example:
[0,0,0,1]//1
[1,1,1,1]//15
solution:
<script type="text/javascript">
const binaryArrayToNumber = arr => {
// 转换成number
var number = arr.join('');
// console.log(number);
// 将二进制转换成十进制
var result = parseInt(number,2);
return result;
};
// 验证
console.log(binaryArrayToNumber([0,0,0,1]));//1
console.log(binaryArrayToNumber([1,1,1,1]));//15
</script>
【6】Complete the square sum function so that it squares each number passed into it and then sums the results together.(即 将数组中每位数字求平方相加)
example:
[1,2,2]//9
[1,2]//5
solution:
<script type="text/javascript">
function squareSum(numbers){
var sum=0;
for(var i=0;i<numbers.length;i++){
sum += Math.pow(numbers[i],2);
}
return sum;
}
// 验证
console.log(squareSum([1,2]));//5
</script>
【7】Given: an array containing hashes of names.Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.
(除最后两个名称外,其余名称用逗号分隔,它们应该用&号分隔。)
example:
list([ {
name: 'Bart'}, {
name: 'Lisa'}, {
name: 'Maggie'} ])
// returns 'Bart, Lisa & Maggie'
list([ {
name: 'Bart'}, {
name: 'Lisa'} ])
// returns 'Bart & Lisa'
list([ {
name: 'Bart'} ])
// returns 'Bart'
list([])
// returns ''
思路:
- 先获取到名称;
- 获取到输入数组的长度。如果长度为0,直接返回’’;否则获取到name属性放在新数组中
- 然后根据题目要求的分隔符进行分隔。
solution:
<script type="text/javascript">
function list(names){
var arr =[];
// 获取到输入数组的长度
var length = names.length;
// 如果长度为0,直接返回'';否则获取到name属性放在新数组中
if(length !=0){
for(var i=0;i<names.length-1;i++){
arr.push(names[i].name);
}
}else{
return '';
}
// 除最后两个名称外,其余名称用逗号分隔,它们应该用&号分隔
var str = arr.join(', ');
if(str !=''){
str = str + ' & ' + names[length-1].name;
}else{
str = names[length-1].name;
}
return str;
}
// 验证
console.log(list([{
name: 'Bart'},{
name: 'Lisa'},{
name: 'Maggie'},{
name: 'Homer'},{
name: 'Marge'}]));//'Bart, Lisa, Maggie, Homer & Marge',"Must work with many names"
console.log(list([{
name: 'Bart'},{
name: 'Lisa'}]));//Bart&Lisa
console.log(list([{
name: 'Bart'}]));//Bart
console.log(list([]));//''
</script>
【8】You are going to be given a word. Your job is to return the middle character of the word. If the word’s length is odd, return the middle character. If the word’s length is even, return the middle 2 characters.(如果单词的长度是奇数,则返回中间的字符。如果单词的长度是偶数,则返回中间的2个字符。)
example:
Kata.getMiddle("test") should return "es"
Kata.getMiddle("testing") should return "t"
Kata.getMiddle("middle") should return "dd"
Kata.getMiddle("A") should return "A"
solution:
<script type="text/javascript">
function getMiddle(s){
var length = s.length;
// 获取到中间index
var index = parseInt(length/2);
var arr = [];
console.log(index);
// 将字符串拆分成数组
arr = s.split('');
if(length % 2 ==0){
return arr[index-1] + arr[index];
}else{
return arr[index];
}
}
// 验证
console.log(getMiddle("test"));//es
console.log(getMiddle("testing"));//t
console.log(getMiddle("A"));//A
</script>
【9】There is an array with some numbers. All numbers are equal except for one.(即 找出数组中唯一一个不同的数字)
example:
findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2
findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55
solution:
<script type="text/javascript">
function findUniq(arr) {
for(var i=0;i<arr.length;i++){
for(var j=i;j<arr.length;j++){
if(arr[i] != arr[j]){
return arr[j];
}
}
}
}
// 验证
console.log(findUniq([ 1, 1, 1, 2, 1, 1 ]));//2
console.log(findUniq([ 0, 0, 0.55, 0, 0 ]));//0.55
</script>
【10】 For simplicity, you’ll have to capitalize each word, check out how contractions are expected to be in the example below.(即 将每个单词首字母大写)
example:
Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real"
思路:
- 转换成首字母大写
- 先全部转为小写,然后将首字母转换成大写
solution:
<script type="text/javascript">
String.prototype.toJadenCase = function () {
var arr = this.toLowerCase().split(" ");
console.log(arr);
//遍历字符数组
for(var i = 0;i < arr.length;i++){
//把第一个字符变为大写
arr[i] = arr[i][0].toUpperCase() + arr[i].substring(1,arr[i].length);
}
//加上空格,返回原模式的字符串
return arr.join(" ");
};
// 验证
var str = "How can mirrors be real if our eyes aren't real";
console.log(str.toJadenCase());//"How Can Mirrors Be Real If Our Eyes Aren't Real"
</script>
【11】Given two arrays a
and b
write a function comp(a, b)
(compSame(a, b)
in Clojure) that checks whether the two arrays have the “same” elements, with the same multiplicities. “Same” means, here, that the elements in b
are the elements in a
squared, regardless of the order.(即 检查这两个数组是否具有“相同”的元素和相同的多重性。"相同"的意思是,在这里,b中的元素是a的平方中的元素,无论顺序如何。)
example:
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19]
思路:
- 先将数组中的元素进行平方,放入到新的数组中
- **newArr.sort().toString() == array2.sort().toString()**用来判断两数组的元素是否全部相同
solution:
<script type="text/javascript">
function comp(array1, array2){
var newArr = [];
for(var i=0;i<array1.length;i++){
newArr.push(Math.pow(array1[i],2));
}
// 判断两个数组的元素是否全部相同
return (newArr.sort().toString() == array2.sort().toString());
}
// 验证
a1 = [121, 144, 19, 161, 19, 144, 19, 11];
a2 = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19];
console.log(comp(a1,a2));//true
</script>
【12】Given an array of integers, remove the smallest value. Do not mutate the original array/list. If there are multiple elements with the same value, remove the one with a lower index. If you get an empty array/list, return an empty array/list.Don’t change the order of the elements that are left.==(即 给定一个整数数组,删除最小的值。不要改变原来的数组/列表。如果有多个具有相同值的元素**,则删除下标较低的元素。如果你得到一个空数组/列表,返回一个空数组/列表。不要改变剩下元素的顺序。)==
example:
removeSmallest([1,2,3,4,5]) = [2,3,4,5]
removeSmallest([5,3,2,1,4]) = [5,3,2,4]
removeSmallest([2,2,1,2,1]) = [2,2,2,1]
思路:
- 先检查数组长度是否为0,如果为空数组,则返回空数组;
- 否则寻找数组中的最小元素;
- 如果只有一个直接删除;如果有多个,则找到下标最低的元素删除。
solution:
<script type="text/javascript">
function removeSmallest(numbers) {
// 获取到传入数组的长度
var length = numbers.length;
// console.log(length);
// 如果长度为0则返回空数组,否则寻找数组中最小元素
if(length!=0){
// 寻找数组中的最小元素
var min = Math.min(...numbers);
// console.log(min);
// 获取到最小元素的index数组
var index = [];
for(var i=0;i<length;i++){
if(min == numbers[i]){
index.push(i);
}
}
// 获取到最小元素的最小index,并删除
var indexMin = Math.min(...index);
// console.log('indexMin'+indexMin);
numbers.splice(indexMin,1);
// console.log('numbers'+numbers);
return numbers;
}else{
return [];
}
}
// 验证
console.log(removeSmallest([1,2,3,4,5]));//[2,3,4,5]
console.log(removeSmallest([2,2,1,2,1]) );//[2,2,2,1]
</script>
以上为自己思路供大家参考,可能有更优的思路。