网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

比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.
  *
  * 

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对创新互联的支持。


分享标题:比Math类库abs()方法性能更高的取绝对值方法介绍
标题路径:http://bjjierui.cn/article/pspeji.html

其他资讯