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

作者:简简单单OnlineZuozuo 时间:2023-10-14 07:51:36 

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;
}

来源:https://blog.csdn.net/qq_15071263/article/details/77142001

标签:math,绝对值,abs()
0
投稿

猜你喜欢

  • 基于Java解决华为机试之字符串加解密 

    2022-10-12 17:32:39
  • Spring MVC URL地址映射的示例代码

    2022-12-09 19:53:33
  • Android仿百度谷歌搜索自动提示框AutoCompleteTextView简单应用示例

    2022-12-07 07:30:59
  • 浅谈Spring @Async异步线程池用法总结

    2021-09-11 07:12:08
  • Winform控件优化Paint事件实现圆角组件及提取绘制圆角的方法

    2022-04-04 15:41:13
  • Java使用过滤器防止SQL注入XSS脚本注入的实现

    2021-09-14 18:17:19
  • windows定时器配置执行java jar文件的方法详解

    2023-04-17 16:40:21
  • java面试try-with-resources问题解答

    2023-09-03 15:08:01
  • Android 实现闪屏页和右上角的倒计时跳转实例代码

    2022-12-10 17:32:32
  • Android虚拟机Dalvik和ART科普

    2022-12-31 06:02:28
  • springboot logback调整mybatis日志级别无效的解决

    2023-05-03 05:36:21
  • maven springboot如何将jar包打包到指定目录

    2022-12-09 00:40:25
  • 单例模式 分析代码优化方法

    2021-07-28 15:49:51
  • Java实现画图 给图片底部添加文字标题

    2023-03-28 23:23:06
  • C#中的multipart/form-data提交文件和参数

    2021-09-26 09:40:19
  • Android中实现长按修改ListView对象的内容

    2022-04-13 15:09:08
  • Android最简单的限制输入方法(只包含数字、字母和符号)

    2022-01-22 00:15:45
  • word ppt excel文档转换成pdf的C#实现代码

    2022-10-10 16:51:54
  • Java实现SMS短信通发送手机验证码案例讲解

    2022-05-14 22:37:57
  • Android如何监听屏幕旋转

    2021-12-15 06:12:50
  • asp之家 软件编程 m.aspxhome.com