码迷,mamicode.com
首页 > 编程语言 > 详细

java简单的判断奇偶数方法

时间:2015-06-04 06:15:33      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:android 拾荒者老大 java 奇偶数

    今天找提高代码性能的方法,刚好看到这篇文章里http://www.cnblogs.com/chinafine/articles/1787118.html

提到的.

1. 奇偶判断 
不要使用 i % 2 == 1 来判断是否是奇数,因为i为负奇数时不成立,请使用 i % 2 != 0 来判断是否是奇数,或使用 高效式 (i & 1) != 0来判断。 

   想着今天还用%2来判断,虽然传入的值不会出现负数,但难保以后不会掉坑里,所以留意了一下高效式.高效式,一点印象都没有.赶紧测试一下

(i & 1)

//两个只要有一个是偶数就为等于0

//两个都是奇数等于1

然后发现基本没再用位运算符了与(&)、非(~)、或(|)、异或(^)

现在只用(||)(&&)

http://blog.csdn.net/vebasan/article/details/6193916

看了一下这个,都是转2进制再运算.测了一下,发现太麻烦了,还是别拿这个来装逼的好,万一自己也忘了就麻烦了.

                System.out.println(13&17);//1
		System.out.println(12&17);//0
		System.out.println(17&12);//0
		System.out.println(12&18);//0
		System.out.println(-12&18);//16
		System.out.println(-12&-18);//28
		System.out.println(12&-18);//12
		System.out.println(-3&-7);//-7
		System.out.println(4|1);//5
		System.out.println(13|1);//13
		System.out.println(13|17);//29
		System.out.println(12|17);//29
		System.out.println(17|12);//29
		System.out.println(12|18);//30
		System.out.println(129&128);//128
		System.out.println(129|128);//129



文章还说到使用位移操作(>>)(<<),呵呵,那时候也就听听,那么麻烦的事,装逼效果不高

九、使用移位操作来代替‘a / b‘操作 

"/"是一个很“昂贵”的操作,使用移位操作将会更快更有效。 

例子: 

public class sdiv {
    public static final int num = 16;
    public void calculate(int a) {
        int div = a / 4;            // should be replaced with "a >> 2".
        int div2 = a / 8;         // should be replaced with "a >> 3".
        int temp = a / 3;
    }
}



更正: 

public class sdiv {
    public static final int num = 16;
    public void calculate(int a) {
        int div = a >> 2;  
        int div2 = a >> 3;
        int temp = a / 3;       // 不能转换成位移操作
    }
}



十、使用移位操作代替‘a * b‘ 

同上。 
[i]但我个人认为,除非是在一个非常大的循环内,性能非常重要,而且你很清楚你自己在做什么,方可使用这种方法。否则提高性能所带来的程序晚读性的降低将是不合算的。 

例子: 

public class smul {
    public void calculate(int a) {
        int mul = a * 4;            // should be replaced with "a << 2".
        int mul2 = 8 * a;         // should be replaced with "a << 3".
        int temp = a * 3;
    }
}



更正: 

package opt;
public class smul {
    public void calculate(int a) {
        int mul = a << 2;  
        int mul2 = a << 3;
        int temp = a * 3;       // 不能转换
    }
}


本文出自 “苍蝇学android” 博客,请务必保留此出处http://qq445493481.blog.51cto.com/9545543/1658144

java简单的判断奇偶数方法

标签:android 拾荒者老大 java 奇偶数

原文地址:http://qq445493481.blog.51cto.com/9545543/1658144

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!