? ? ? ?位操作的速度比其他方法的效率高了太多,同时也提高了我们的代码逼格,我们熟知的Integer的底层代码就用了很多的位操作;我们用几个例子来试验一下:
①判断奇偶数
?
class="java">import java.util.Scanner; /** * Created by Taoyongpan on 2017/11/7. * 按位与运算判断奇偶数 */ public class test1 { public static void main(String[] args){ Scanner sc = new Scanner(System.in); while (sc.hasNext()){ int n = sc.nextInt(); if (judge(n)==true){ System.out.println(n+"是奇数"); }else { System.out.println(n+"是偶数"); } } } static boolean judge(int n){ return (n & 1)==1; } }
?②不使用乘法,实现 n*7
?
?
package study.weiyunsuan;
import java.util.Scanner;
/**
* Created by Taoyongpan on 2017/11/7.
* 不使用乘法,实现 n*7
*/
public class test2 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while (sc.hasNext()){
int n = sc.nextInt();
System.out.println((n<<3)-n);
}
}
}
?③一个整数,要求去掉它的二进制表示法的最后一次出现的1,例如, 110,去掉最后一个1就是100
?
?
package study.weiyunsuan;
import java.util.Scanner;
/**
* Created by Taoyongpan on 2017/11/7.
* 一个整数,要求去掉它的二进制表示法的最后一次出现的1,例如, 110,去掉最后一个1就是100
*/
public class test3 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while (sc.hasNext()){
int n = sc.nextInt();
System.out.println(n&(n-1));
}
}
}
?④计算二进制中1的个数
?
?
package study.weiyunsuan;
import java.util.Scanner;
/**
* Created by Taoyongpan on 2017/11/7.
* 计算二进制中1的个数
*/
public class test4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Integer m;
while (sc.hasNext()){
int n = sc.nextInt();
int num = 0;
while (n!=0){
n = n&(n-1);
num++;
}
System.out.println(num);
}
}
}
?⑤Integer的源代码使用案例
static void getChars(int i, int index, char[] buf) {
int q, r;
int charPos = index;
char sign = 0;
if (i < 0) {
sign = '-';
i = -i;
}
// Generate two digits per iteration
while (i >= 65536) {
q = i / 100;
// really: r = i - (q * 100);
r = i - ((q << 6) + (q << 5) + (q << 2));
i = q;
buf [--charPos] = DigitOnes[r];
buf [--charPos] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i <= 65536, i);
for (;;) {
q = (i * 52429) >>> (16+3);
r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...
buf [--charPos] = digits [r];
i = q;
if (i == 0) break;
}
if (sign != 0) {
buf [--charPos] = sign;
}
}
?
?