美文网首页
2020-05-17 5 kyu Simple fraction

2020-05-17 5 kyu Simple fraction

作者: 苦庭 | 来源:发表于2020-05-17 06:11 被阅读0次

https://www.codewars.com/kata/556b85b433fb5e899200003f

My answer / AC

var gcd = function(a,b){return (!b) ? a : gcd(b, a%b);};
function mixedFraction(s){
  //your code here
  var p = s.split("/");
  var top = p[0], bottom = p[1];
  if(bottom == 0) throw ZeroDivisionError;
  if(top == 0) return "0";
  
  var sign = (top*bottom)<0 ? "-" : "";
  top = top.replace(/-/, "");
  bottom = bottom.replace(/-/, "");
  var num = Math.floor(top/bottom);
  var g = gcd(top, bottom);
  var frac = g==1 ? (top-num*bottom)+"/"+bottom : ((top-num*bottom)/g)+"/"+(bottom/g);
  return sign + (num?num:"") + (num && frac[0]!=0?" ":"") + (frac[0]==0?"":frac);
}

Best answer

function mixedFraction(s){
//input s will be a simple fraction i.e. "4/3", "-10/7", "-22/7"
  var fraction = s.split("/").map(val => Number(val)),
      numerator = fraction[0],
      denominator = fraction[1],
      integer = 0;
  
  //anything divided by 0 produces an error
  if (denominator === 0) {
      throw new Error("Division by zero");
  }
  
  //0 divided by anything is 0
  if (numerator === 0) {
    return "0";
  }
  
  /* calculate gcf and divide numerator and denominator by
     it to reduce improper fraction as much as possible */
  var gcf = greatestCommonFactor(numerator, denominator);
      numerator /= gcf;
      denominator /= gcf;
  
  /* calculate the integer and numerator for
     mixed fraction; round integer down */
  integer += ~~(numerator / denominator);
  numerator %= denominator;
  
  //if output is a mixed number
  if (integer) {
      //checks to see if fraction will be negative
      if (numerator < 0 || denominator < 0) {
        //integer needs proper sign
        integer *= (integer < 0) ? 1 : -1;
      }
      return (numerator !== 0) 
      //integer is signed already - make numerator and denominator positive
              ? `${integer} ${Math.abs(numerator)}/${Math.abs(denominator)}` 
              : `${integer}`;
  }
  
  //if output is a simple fraction
  else {
    if (denominator < 0) {
      //make sure numerator is negative
      numerator *= (numerator < 0) ? 1 : -1;
    }
    return `${numerator}/${Math.abs(denominator)}`;
  }
}

/* calculates gcf utilizing Euclid's algorithm
   https://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm */
function greatestCommonFactor(a, b) {
  return (b === 0) ? a : greatestCommonFactor(b, a % b);
}

好在哪?

  • 解释得非常好,思路清晰,非常详尽。
  • ~~(a/b)能够得到a除以b的结果的整数部分(等于Math.floor)

Recap

  • 记住辗转相除法了。

相关文章

网友评论

      本文标题:2020-05-17 5 kyu Simple fraction

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