/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Test;
import java.util.Arrays;
/**
*
* @author Administrator
*/
public class DFS {
public static void main(String[] args) {
byte b =7;
//解法一
int num1 =Count1(b);
System.out.println("num1="+num1);
//解法二
int num2 =Count2(b);
System.out.println("num2="+num2);
//解法三
int num3 = Count3(b);
System.out.println("num3="+num3);
//扩展问题一 这里用的是每次计算最低八位,然后向右移八位;其实方法有很多啦
int ss = 775;
int num4 = Count4(ss);
System.out.println("num4="+num4);
//扩展问题二 异或后计算1的个数
byte a =7;
int number = Compare(a,b);
System.out.println("number="+number);
}
private static int Count1(byte b) {
int num =0;
while(b!=0){
if(b%2==1){
num++;
}
b= (byte) (b/2);
}
return num;
}
private static int Count2(byte b) {
int num =0;
while(b!=0){
num +=b & 0x01; //与运算
b =(byte)(b>>>1); //右移补0
}
return num;
}
private static int Count3(byte b) {
int num =0;
while(b!=0){
b = (byte)(b&(b-1));
num++;
}
return num;
}
private static int Count4(int b) {
int num =0;
int nn =255;
while(b !=0){
int a = b&nn;
num+=Count5(a);
b=b>>8;
}
return num;
}
private static int Count5(int b) {
int num =0;
while(b!=0){
num +=b & 0x01; //与运算
b =b>>>1; //右移补0
}
return num;
}
private static int Compare(byte a,byte b) {
byte bb = (byte)(a^b);
int num =Count3(bb);
return num;
}
}
运行结果run:
num1=3
num2=3
num3=3
number=0
num4=5
运行结果run:
num1=3
num2=3
num3=3
number=0
num4=5