【求二进制中1的个数】
先普及一哈位逻辑运算符的知识
op1 | op2 | op1&op2 |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
op1 | op2 | op1Iop2 |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
op1 | op2 | op1^op2 |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
第一种方法
n&1的是意思 判断最后一位是否为1
public class Test{
public static int countOne(int n) {
int count=0;
while(n>0) {
if((n&1)==1)
count++;
n>>=1;
}
return count;
}
}
第二种
public class Test{
public static int countOne(int n) {
int count=0;
while(n>0) {
if(n!=0)
n=n&(n-1);
count++;
}
return count;
}
}
【统计一行字符中有多少个单词】
判断每个字符是否为空 空则count+1 不空则继续往后判断
public class Test_plus {
public static int wordCount(String s) {
int word=0;
int count=0;
for(int i=0;i<s.length();i++) {
if(s.charAt(i)==' ')
word=0;
else if(word==0) {//非空格且 word不等于0则word设为1
word=1;
count++;
}
}
return count;
}
}
【判断一个数是否是2的n次方】
方法1
从1即2^0 开始与n比较 相等则返回true 每次往左移一位 2^1 2^2依次比较
public class Test{
public static boolean isPower(int n) {
if(n<1)return false;
int i=1;
while(i<=n) {
if(i==n)return true;
i<<=1;
}
return false;
}
}
方法2
public class Test{
public static boolean isPower(int n) {
if(n<1)return false;
int m=n&(n-1);
return m==0;
}
}
【不用比较运算得到2个数中的较大或较小的值】
a+b加上差值 或减去差值 再除以2 妙不可言!牛批!
public class Test_plus {
public static int max(int a,int b) {
return (a+b+Math.abs(a-b))/2;
}
public static int min(int a,int b) {
return(a+b-Math.abs(a-b))/2;
}
}
【移位运算实现最快乘法】
public calss Muti{
//n表示左移的次数 ,用循环来控制左移 每次左移一次
public static int powerN(int m,int n){
for(int i=0;i<n;i++)
m=m<<1;
return m;
}
public static void main(String[] args){
System.out.println("3 * 8 = "+powerN(3,3));
}
}