HuangXiZhou / blog

自以为历尽沧桑,其实刚蹒跚学步;自以为掌握了竞争的秘密,其实远没有竞争的资格

Home Page:https://blog.trevor.top

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

【codewars】Math Issues

HuangXiZhou opened this issue · comments

原题

Oh no, our Math object was "accidently" reset. Can you re-implement some of those functions? We can assure, that only non-negative numbers are passed as arguments. So you don't have to consider things like undefined, null, NaN, negative numbers, strings and so on.

Here is a list of functions, we need:

  • Math.round()
  • Math.ceil()
  • Math.floor()

题意解析

手动实现 Math.round() Math.ceil() 以及 Math.floor() 方法

解题思路

  1. 利用正则匹配整数及小数位
  2. 进行判断,返回数值

我的代码

// 四舍五入
Math.round = function(number) {
  const Integer = +number.toString().match(/^[1-9]\d*|0$/)
  const decimals = +number.toString().match(/\.\d*[1-9]\d*$/)
  return decimals < 0.5 
          ? Integer
          : Integer + 1
}

// 向上取整
Math.ceil = function(number) {
  const Integer = +number.toString().match(/^[1-9]\d*|0$/)
  const decimals = +number.toString().match(/\.\d*[1-9]\d*$/)
  return decimals === 0 
          ? Integer
          : Integer + 1
}

// 向下取整
Math.floor = function(number) {
  return Integer = +number.toString().match(/^[1-9]\d*|0$/)
}

最佳代码

Math.round = function(number) {
  return (number - parseInt(number) >= 0.5) ? parseInt(number) + 1 : parseInt(number) ;
};

Math.ceil = function(number) {
  return (parseInt(number) === number) ? number : parseInt(number) + 1;
};

Math.floor = function(number) {
  return parseInt(number);
};

总结

最佳代码使用 parseInt() 方法取得整数位,通过判断相减得到的小数位来返回相应的结果