How do I get the absolute value of an integer without using Math.abs?

强颜欢笑 提交于 2020-02-02 12:17:12

问题


How do I get the absolute value of a number without using math.abs?

This is what I have so far:

function absVal(integer) {
    var abs = integer * integer;
    return abs^2;
}

回答1:


You can use the conditional operator and the unary negation operator:

function absVal(integer) {
  return integer < 0 ? -integer : integer;
}



回答2:


You can also use >> (Sign-propagating right shift)

function absVal(integer) {
    return (integer ^ (integer >> 31)) - (integer >> 31);;
}

Note: this will work only with integer




回答3:


Since the absolute value of a number is "how far the number is from zero", a negative number can just be "flipped" positive (if you excuse my lack of mathematical terminology =P):

var abs = (integer < 0) ? (integer * -1) : integer;

Alternatively, though I haven't benchmarked it, it may be faster to subtract-from-zero instead of multiplying (i.e. 0 - integer).




回答4:


There's no reason why we can't borrow Java's implementation.

    function myabs(a) {
      return (a <= 0.0) ? 0.0 - a : a;
    }

    console.log(myabs(-9));

How this works:

  • if the given number is less than or zero
    • subtract the number from 0, which the result will always be > 0
  • else return the number (because it's > 0)



回答5:


Check if the number is less than zero! If it is then mulitply it with -1;



来源:https://stackoverflow.com/questions/30268801/how-do-i-get-the-absolute-value-of-an-integer-without-using-math-abs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!