判断一个整数的奇偶性,是否为2的幂?
public class Integer {
// 2的幂
public static boolean isPower2(int n) {
return (((n - 1) & n) == 0);
}
// 奇数判断
public static boolean isOdd(int n) {
return ((n & 0x01) != 0);
}
// 偶数判断
public static boolean isEven(int n) {
return ((n & 0x01) == 0);
}
// 最大公约数
public static int getGCD(int a, int b) {
if ((a <= 0) || (b <= 0))
return -1;
int tmp;
if (a > b) {
tmp = a;
a = b;
b = tmp;
}
do {
tmp = a;
a = b % a;
b = tmp;
} while (a != 0);
return b;
}
// 最小公倍数
public static long getLCM(int a, int b) {
if ((a <= 0) || (b <= 0))
return -1;
long mul = a * b;
return (mul / getGCD(a, b));
}
/**
* @param args
*/
public static void main(String[] args) {
/*
* for (int i = 0; i <= 1024; i++) { System.out.println(i + ":\t" +
* Integer.isPower2(i)); }
*/
for (int i = -20; i <= 20; i++) {
System.out.println(i + ":\t" + Integer.isEven(i) + "\t"
+ Integer.isOdd(i));
}
int a = 27, b = 36;
System.out.println("GCD(" + a + "," + b + ")=" + Integer.getGCD(a, b));
System.out.println("LCM(" + a + "," + b + ")=" + Integer.getLCM(a, b));
}
}