标签:
环境:jdk 1.7。
package hellojava;
public class HelloJava {
// 用取余运算
public boolean isEven01(int num) {
if (num % 2 == 0) {
return true;
} else {
return false;
}
}
// 如果没有取余运算符,自己做一个
public boolean isEven02(int num) {
int tmp = num/2;
if (num-tmp*2 == 0) {
return true;
} else {
return false;
}
}
// 再换个思路
public boolean isEven03(int num) {
String numStr = new Integer(num).toString();
char lastChar = numStr.charAt(numStr.length()-1);
switch(lastChar) {
case ‘0‘:
case ‘2‘:
case ‘4‘:
case ‘6‘:
case ‘8‘:
return true; // 没必要break了
default:
return false;
}
}
public static void main(String[] args) {
HelloJava hj = new HelloJava();
System.out.println(hj.isEven01(10));
System.out.println(hj.isEven02(10));
System.out.println(hj.isEven03(10));
System.out.println(hj.isEven01(11));
System.out.println(hj.isEven02(11));
System.out.println(hj.isEven03(11));
}
}
执行结果:
true
true
true
false
false
false
另外,负整数的除2和取余要注意一下:
package hellojava;
public class HelloJava {
public static void main(String[] args) {
System.out.println(-10/2);
System.out.println(-10%2);
System.out.println(-11/2);
System.out.println(-11%2);
}
}
运行结果如下:
-5
0
-5
-1
标签:
原文地址:http://my.oschina.net/letiantian/blog/415860