Math.abs()的實(shí)現(xiàn)源碼
通過(guò)三目運(yùn)算符判斷a是否小于0來(lái)實(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 類(lèi)型的任何正數(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ì)武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注