[英]Java: How to find if an Integer is a multiple of 2 without using division or modulo operator
回想偶數的二進制表示將最低有效位設置為零。 現在解決方案很簡單:使用按位AND將最后一位掩碼為1
,並將結果與零進行比較。 如果你得到零,那么數字是均勻的; 否則,這很奇怪。
boolean isEven(int a) {
return (a & 1) == 0;
}
當你執行a & 1
,你會得到1或0的結果,具體取決於最后一位的值。 對此的術語是“位屏蔽”:在這種情況下, 1
用作位掩碼。
int i = 5; if ((i & 0x1) == 0) { System.out.println("It's a multiple of 2"); } else { System.out.println("It's NOT a multiple of 2"); }
你也可以使用移位,向右移一位並向后移,這也相當於除以2並向后移2
boolean isEven(int val){
if(((val>>1)<<1) == val){
return true;
}
}
一個簡單的方法就是,
int no=5;
String str=""+no;
if((str.length()-1).equals("2")||(str.length()-1).equals("4")||(str.length()-1).equals("6")||(str.length()-1).equals("8")||(str.length()-1).equals("0")||)
System.out.println("Yes");
System.out.println("No");
就如此容易。 希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.