Math Issues
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()
题目意思是js 的内置对象Math 不能用了,让我们来修复Math.round()这些方法。
只要能想到parseInt()这个方法,这个问题就很简单了。我的常规解法:
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); };
某神的解法:
Math.round = function(number) { return Math.floor(number + 0.5); }; Math.ceil = function(number) { return (number | 0) + (number % 1 !== 0 ? 1 : 0); }; Math.floor = function(number) { return number | 0; };
看了某神的解法,瞬间感觉自己长了个假脑子,不说了,我去哭一会儿,把脑子里的水倒一倒。
人生如逆旅,我亦是行人