美文网首页
Clever Answers in Codewar(Javasc

Clever Answers in Codewar(Javasc

作者: _敏讷 | 来源:发表于2017-10-21 10:36 被阅读0次

    problem:

    createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) // => returns "(123) 456-7890"
    

    clever solution:

    function createPhoneNumber(numbers){
      var format = "(xxx) xxx-xxxx";
      
      for(var i = 0; i < numbers.length; i++)
      {
        format = format.replace('x', numbers[i]);
      }
      
      return format;
    }
    

    2.problem:

     persistence(39) === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
                           // and 4 has only one digit
    
     persistence(999) === 4 // because 9*9*9 = 729, 7*2*9 = 126,
                            // 1*2*6 = 12, and finally 1*2 = 2
    
     persistence(4) === 0 // because 4 is already a one-digit number
    

    one line solution:
    使用了递归

    const persistence = num => {
      return `${num}`.length > 1 ? 1 + persistence(`${num}`.split('').reduce((a, b) => a * +b)) : 0;
    }
    
    1. problem :

    Your task is to sort a given string. Each word in the String will contain a single number. This number is the position the word should have in the result.

    Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).

    If the input String is empty, return an empty String. The words in the input String will only contain valid consecutive numbers.

    For an input: "is2 Thi1s T4est 3a" the function should return "Thi1s is2 3a T4est"

    one line & cleverest solution:

    function order(words) {
      return words.split(' ').sort( (a, b) => a.match(/\d/) - b.match(/\d/)).join(' ')
    }
    
    1. 将10进制转化为2进制数

    我的方法:

    var turnBits = function(n) {
      let bits = ''
      while(n) {
        bits = n % 2 + bits
        n = Math.floor(n / 2)
      }
      return bits
    };
    

    JS的原生方法:

    n.toString(2)
    
    1. 检测单一种类括号是否闭合
      solution:
    function validParentheses(parens){
      var n = 0;
      for (var i = 0; i < parens.length; i++) {
        if (parens[i] == '(') n++;
        if (parens[i] == ')') n--;
        if (n < 0) return false;
      }
      return n == 0;
    }
    

    相关文章

      网友评论

          本文标题:Clever Answers in Codewar(Javasc

          本文链接:https://www.haomeiwen.com/subject/nfciuxtx.html