编程之美2.1求二进制数中1的个数及扩展问题Java版

 /* 

 * 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值