CodeWars Weekly Challenge 1

CodeWars Weekly Challenge 1

1 问题描述

Create a function which answers the question “Are you playing banjo?”.If your name starts with the letter “R” or lower case “r”, you are playing banjo!The function takes a name as its only argument, and returns one of the following strings:
name + " plays banjo"
name + " does not play banjo"

  • mine
function areYouPlayingBanjo(name) {
  if(name.substring(0,1)=='R'||name.subString(0,1)=='r'){
  	name+=" plays banjo";
  }else{
  	name+=" does not play banjo";
  }
  return name;
}
  • better
function areYouPlayingBanjo(name) {
  return name + (name[0].toLowerCase() == 'r' ? ' plays' : ' does not play') + " banjo";
}

2 问题描述

Definition
A number is called Automorphic number if and only if its square ends in the same digits as the number itself.
Task
Given a number determine if it Automorphic or not .

  • mine
function automorphic(n){
  var length1=n.toString().length;
  var length2=(n*n).toString().length;
  return (n*n).toString().substring(length2-length1,length2)==n.toString()?"Automorphic":"Not!!";
}
  • better
const automorphic = n => String(n*n).endsWith(String(n)) ? "Automorphic" : "Not!!" ;

3 问题描述

Description:
Implement the method map, which accepts a linked list (head) and a mapping function, and returns a new linked list (head) where every element is the result of applying the given mapping method to each element of the original list.

Make sure you do not modify the original list!

For example: Given the list: 1 -> 2 -> 3, and the mapping function x => x * 2, map should return 2 -> 4 -> 6

The linked list is defined as follows:
function Node(data, next = null) {
this.data = data;
this.next = next;
}
Note: the list may be null and can hold any type of value.

  • Answer
function map(head, f) {
  return !head ? null : new Node(f(head.data), map(head.next, f));
}

4问题描述

Description:
Given the string representations of two integers, return the string representation of the sum of those integers.

For example:

sumStrings(‘1’,‘2’) // => ‘3’

  • Answer
function sumStrings(a,b) { 
  var res='',c=0;
  a=a.split('');
  b=b.split('');
  while(a.length||b.length||c){//pop() 方法用于删除并返回数组的最后一个元素
   c+=~~a.pop()+~~b.pop();
   res=c%10+res;
   c=c>9;//是否进位
  }
  return res.replace(/^0+/,'');//替代开头的多个0,比如sumStrings('00103', '08567') - Expected: '8670', instead got: '08670'
}

猜你喜欢

转载自blog.csdn.net/ChristineAS/article/details/86410426
今日推荐