比Math類庫abs()方法性能更高的取絕對(duì)值方法介紹
Math.abs()的實(shí)現(xiàn)源碼
通過三目運(yùn)算符判斷a是否小于0來實(shí)現(xiàn)
/**
* 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;
}
如果換種方式,性能會(huì)有20%左右的提升
代碼如下
/**
* Created by 譚健 2017/8/13. 12:47.
* All Rights Reserved
*
* int 是 32 位數(shù)據(jù)
* int 類型的任何正數(shù)右移31位 = 0,任何負(fù)數(shù)右移31位 = 1
* 溢出 31 位截?cái)?,空?31 位補(bǔ)1,得到-1
* a>>31 可以得到該數(shù)的符號(hào)位 + 還是 -
* 如果 a>>31 + ,那么 a ^ 0 = a ,如果 a>>31 - ,那么 a ^ -1 翻轉(zhuǎn) a 的二進(jìn)制
*
* @param a int a
* @return a 的絕對(duì)值
*/
public static int abs(int a){
return (a^(a>>31))-(a>>31);
}
奇數(shù)偶數(shù)的判斷
/**
* 一般普遍采用 n % 2 == 0 的方式
* 但是如果換成位運(yùn)算方式,效率會(huì)比前者好很多
*
* 在二進(jìn)制中,末位為 0 必然是偶數(shù),否則是奇數(shù),并且不論正負(fù)
* 所以,是什么數(shù),看看末位就行了
*
* @param a long a
* @return 如果是奇數(shù),返回true,否則返回false
*/
public static boolean isOdd(long a){
return (a & 1) == 1;
}
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
DevExpress實(shí)現(xiàn)TreeList向上遞歸獲取符合條件的父節(jié)點(diǎn)
這篇文章主要介紹了DevExpress實(shí)現(xiàn)TreeList向上遞歸獲取符合條件的父節(jié)點(diǎn),需要的朋友可以參考下2014-08-08
C#使用DevExpress中的SplashScreenManager控件實(shí)現(xiàn)啟動(dòng)閃屏和等待信息窗口
這篇文章介紹了C#使用DevExpress中的SplashScreenManager控件實(shí)現(xiàn)啟動(dòng)閃屏和等待信息窗口的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-05-05
快速了解如何在.NETCORE中使用Generic-Host建立主機(jī)
這篇文章主要介紹了如何在.NETCORE中使用Generic-Host建立主機(jī),文中代碼非常詳細(xì),可供大家參考,感興趣的朋友不妨閱讀完2020-05-05
C#中out參數(shù)、ref參數(shù)與值參數(shù)的用法及區(qū)別
這篇文章主要給大家介紹了關(guān)于C#中out參數(shù)、ref參數(shù)與值參數(shù)的用法及區(qū)別的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-09-09
C#如何實(shí)現(xiàn)監(jiān)控手機(jī)屏幕(附源碼下載)
這篇文章主要介紹了C#如何實(shí)現(xiàn)監(jiān)控手機(jī)屏幕(附源碼下載),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10

