一种比Math类库abs()方法性能更高的取绝对值的方法

一种比Math类库abs()方法性能更高的取绝对值的方法

#

Math.abs()的实现源码
通过三目运算符判断a是否小于0来实现
/**
     * Returns the absolute value of an {@code int} value.
     * If the argument is not negative, the argument is returned.
     * If the argument is negative, the negation of the argument is returned.
     *
     * <p>Note that if the argument is equal to the value of
     * {@link Integer#MIN_VALUE}, the most negative representable
     * {@code int} value, the result is that same value, which is
     * negative.
     *
     * @param   a   the argument whose absolute value is to be determined
     * @return  the absolute value of the argument.
     */
    public static int abs(int a) {
        return (a < 0) ? -a : a;
    }
如果换种方式,性能会有20%左右的提升
代码如下
 /**
     * Created by 谭健 2017/8/13. 12:47.
     * All Rights Reserved
     *
     * int 是 32 位数据
     * int 类型的任何正数右移31位 = 0,任何负数右移31位 = 1
     * 溢出 31 位截断,空出 31 位补1,得到-1
     * a>>31 可以得到该数的符号位 + 还是 -
     * 如果 a>>31 + ,那么 a ^ 0 = a ,如果 a>>31 - ,那么 a ^ -1 翻转 a 的二进制
     *
     * @param a int a
     * @return a 的绝对值
     */
    public static int abs(int a){
        return (a^(a>>31))-(a>>31);
    }
奇数偶数的判断
/**
     * 一般普遍采用 n % 2 == 0 的方式
     * 但是如果换成位运算方式,效率会比前者好很多
     *
     * 在二进制中,末位为 0 必然是偶数,否则是奇数,并且不论正负
     * 所以,是什么数,看看末位就行了
     *
     * @param a long a
     * @return 如果是奇数,返回true,否则返回false
     */
    public static boolean isOdd(long a){
        return (a & 1) == 1;
    }
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

简简单单OnlineZuozuo

感谢哥哥姐姐的打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值