Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在codewar打怪升级的日子 #28

Open
damoclesX opened this issue Mar 10, 2016 · 0 comments
Open

在codewar打怪升级的日子 #28

damoclesX opened this issue Mar 10, 2016 · 0 comments
Labels

Comments

@damoclesX
Copy link
Owner

在div.io上面看到codewar,于是google,发现可以在上面做javascript的思考题,每次提交自己的解决方案后,看到最佳实践(为得票最高的解决方案)时,:cry:

Isograms

isogram是一个字符串,然后只要这个字符串没有重复的字母(不区分大小写,不管是不是连续),它便是isogram,否则便不是。我的解法:

function isIsogram(str){
  var tmp = str.toLowerCase().split('');
  var res= tmp.filter(function(e, i, arr){
    return arr.indexOf(e) === i;
  });
  return tmp.length == res.length;
}

最佳实践

function isIsogram(str){ 
  return !/(\w).*\1/i.test(str)
}

Is a number prime?

判断一个数是否是质数(素数),我的解法

function isPrime(num) {
  if(num<=1){
    return false;
  }else if([2,3,5,7].indexOf(num) != -1){
    return true;
  }else{
    return !!(num%2 && num%3 && num%5 && num%7);
  }
}

最佳实践

function isPrime(num) {
  for (var i = 2; i < num; i++) if (num % i == 0) return false;
  return num >= 2; 
}

这里的最佳实践有些人不是很赞同,觉得慢,个人觉得挺不错,连哪些是10以内的质数都不需要知道,自动计算。

Find The Parity Outlier

在一个整数数组中,只有一个奇数或者偶数,其他相应都是偶数或者奇数。

function findOutlier(integers){
  var res;
  var odd = integers.filter(function(e){
    if(e%2 != 0){
      res = e;
    };
    return e%2 == 0;
  });

  return odd.length>1 ? res : odd.pop();
}

最佳实践

function findOutlier(int){
  var even = int.filter(a=>a%2==0);
  var odd = int.filter(a=>a%2!==0);
  return even.length==1? even[0] : odd[0];
}

这次这个最佳实践感觉一般了,只是可读性很强

@damoclesX damoclesX added the js label Mar 10, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant