一个 JS 面试题目

看到一个 JS 题:

只允许使用 +-*/ 和 Math.* ,求一个函数 y = f(x, a, b);

当 x > 100 时返回 a 的值,否则返回 b 的值,不能使用 if else 等条件语句,也不能使用  |, ?, 数组

试解如下:

<script>

function transition(x, a, b){

x = Math.max(x, 0); // 先处理负数。

if(x == 100){

   return b;

}

var tmp = Math.ceil(Math.min(Math.max(x - 100, 0), 1));

return a*tmp + b*Math.abs(tmp-1);

}

console.log(transition(101, 1, 0));// 1

console.log(transition(100.5, 1, 0));// 1

console.log(transition(100, 1, 0)); //0

console.log(transition(99.5, 1, 0));// 0

console.log(transition(99, 1, 0));// 0

console.log(transition(-23, 1, 0));// 0

</script>

一般思路是转换为 0, 1 的特殊值问题进行处理。

posted on 2011-09-26 09:28  沙加  阅读(1011)  评论(3编辑  收藏  举报

导航