国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > C# > 正文

比Math類(lèi)庫(kù)abs()方法性能更高的取絕對(duì)值方法介紹

2020-01-24 00:05:54
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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)的支持。

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 云龙县| 长寿区| 体育| 陕西省| 武宁县| 延寿县| 凌云县| 罗定市| 启东市| 淮滨县| 巢湖市| 扶风县| 长阳| 金堂县| 杭锦后旗| 贺州市| 花莲市| 抚顺县| 阆中市| 衡东县| 迭部县| 灵寿县| 盘锦市| 淳安县| 讷河市| 清水县| 凯里市| 南城县| 尼勒克县| 喀喇| 那曲县| 瑞昌市| 雷波县| 台中市| 南汇区| 宜宾县| 安多县| 德兴市| 寿阳县| 同德县| 海原县|