【java/math】位运算判断奇数和取余运算判断奇数的差别
【结论】
位运算稍快一点点。
【代码】
package com.hy.lab.bitcalc; public class Test { public static void main(String[] args){ final int max=1000000000; int oddCnt=0; long startMs=System.currentTimeMillis(); for(int i=0;i<max;i++) { if(isOddByBit(i)){ oddCnt++; } } System.out.println("oddCnt="+oddCnt); long endMs=System.currentTimeMillis(); System.out.println("isOddByBit耗时:"+ms2DHMS(startMs,endMs)); oddCnt=0; startMs=System.currentTimeMillis(); for(int i=0;i<max;i++) { if(isOddByMod(i)){ oddCnt++; } } System.out.println("oddCnt="+oddCnt); endMs=System.currentTimeMillis(); System.out.println("isOddByMod耗时:"+ms2DHMS(startMs,endMs)); } // 位运算判断奇数 private static boolean isOddByBit(int num){ return (num & 1)==1; } // 取余运算判断奇数 private static boolean isOddByMod(int num){ return (num % 2)==1; } private static String ms2DHMS(long startMs, long endMs) { String retval = null; long secondCount = (endMs - startMs) / 1000; String ms = (endMs - startMs) % 1000 + "ms"; long days = secondCount / (60 * 60 * 24); long hours = (secondCount % (60 * 60 * 24)) / (60 * 60); long minutes = (secondCount % (60 * 60)) / 60; long seconds = secondCount % 60; if (days > 0) { retval = days + "d" + hours + "h" + minutes + "m" + seconds + "s"; } else if (hours > 0) { retval = hours + "h" + minutes + "m" + seconds + "s"; } else if (minutes > 0) { retval = minutes + "m" + seconds + "s"; } else if(seconds > 0) { retval = seconds + "s"; }else { return ms; } return retval + ms; } }
输出:
第一次
oddCnt=500000000 isOddByBit耗时:1s359ms oddCnt=500000000 isOddByMod耗时:1s860ms
第二次
oddCnt=500000000 isOddByBit耗时:1s406ms oddCnt=500000000 isOddByMod耗时:1s516ms
第三次
oddCnt=500000000 isOddByBit耗时:1s297ms oddCnt=500000000 isOddByMod耗时:1s547ms
END
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2017-06-30 【Canvas与艺术】绘制绿圈三红五星Premium Quality标志