[7kyu]Battle of the characters (

2017-07-04  本文已影响13人  君肄塵

该算法题来自于 codewars【语言: javascript】,翻译如有误差,敬请谅解~


const sum = str => [...str].map(el=>el.charCodeAt()).reduce((r,v)=>r+v,0);
const battle = (x, y) => sum(x) == sum(y) ? 'Tie!' :( sum(x) > sum(y) ? x : y);
const total = word => [...word].reduce((a,b)=>a+(b.charCodeAt()),0)
const battle = (x, y) => total(x) > total(y) ? x : total(y) > total(x) ? y : 'Tie!'
function battle(x, y) {
      var sumx =0;
      var i = x.length;
      while (i--) {
        sumx += x.charCodeAt(i);
      }  
      var sumy =0;
      i = y.length;
      while (i--) {
        sumy += y.charCodeAt(i);
      }  
      if (sumx == sumy) return 'Tie!';  
      return sumx > sumy ? x: y;
}
function battle(x, y) { 
      let r1 = x.split('').reduce( (a,b) => a+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(b),0);
      let r2 = y.split('').reduce( (a,b) => a+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(b),0);
      return r1 > r2 ? x : r1 < r2 ? y : "Tie!";
}
function battle(x, y) {
      var s1 = 0;
      var s2 = 0;
      x.split("").forEach(function(value){
        s1+=value.charCodeAt()-96;
      });
      y.split("").forEach(function(value){
        s2+=value.charCodeAt()-96;
      });
      return s1>s2? x:s1<s2?y:'Tie!'
}
上一篇 下一篇

猜你喜欢

热点阅读