Finding absolute value of a number without using Math.abs()

后端 未结 10 1537
轮回少年
轮回少年 2021-02-02 11:16

Is there any way to find the absolute value of a number without using the Math.abs() method in java.

10条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-02 12:21

    Although this shouldn't be a bottle neck as branching issues on modern processors isn't normally a problem, but in the case of integers you could go for a branch-less solution as outlined here: http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs.

    (x + (x >> 31)) ^ (x >> 31);
    

    This does fail in the obvious case of Integer.MIN_VALUE however, so this is a use at your own risk solution.

提交回复
热议问题