zoukankan      html  css  js  c++  java
  • N11-该数二进制表示中1的个数

    题目描述

    输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
    package new_offer;
    /**
     * 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
     * @author Sonya
     *
     */
    public class N11_NumberOf1 {
    
    	public int NumberOf1(int n) {
    		String bstring=Integer.toBinaryString(n);//
    		System.out.print("转换成的二进制字符串:   ");
    		System.out.println(bstring);
    		
    		char[]ch=bstring.toCharArray();
    		System.out.print("转换成的二进制数组:   ");
    		System.out.println(ch);
    		int count=0;
    		for(int i=0;i<ch.length;i++) {
    			System.out.print("二进制数组:   "+i+"   ");
    			System.out.println(Integer.valueOf(ch[i]));
    			if(Integer.valueOf(ch[i])==49) count++;//valueof  的值为 字符的ASCLL值
    		}
    		return count;
    		
    	}
    	/**
    	 * 如果一个整数不为0,那么这个整数至少有一位是1。
    	 * 如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0,
    	 * 原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。
    	 * 举个例子:一个二进制数1100,从右边数起第三位是处于最右边的一个1。
    	 *减去1后,第三位变成0,它后面的两位0变成了1,而前面的1保持不变,因此得到的结果是1011.
    	 *我们发现减1的结果是把最右边的一个1开始的所有位都取反了。
    	 *这个时候如果我们再把原来的整数和减去1之后的结果做与运算,
    	 *从原来整数最右边一个1那一位开始所有位都会变成0。
    	 *如1100&1011=1000.也就是说,把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0.
    	 *那么一个整数的二进制有多少个1,就可以进行多少次这样的操作。
    	 * @param n
    	 * @return
    	 */
    	public int NumberOf1_2(int n) {
    		int count = 0;
            while(n!= 0){
                count++;
                n = n & (n - 1);
             }
            return count;
    	}
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		N11_NumberOf1 n11=new N11_NumberOf1();
    		System.out.println(n11.NumberOf1(0));
    	}
    
    }
    

      

  • 相关阅读:
    又玩起了“数独”
    WebService应用:音乐站图片上传
    大家都来DIY自己的Blog啦
    CSS导圆角,不过这个代码没有怎么看懂,与一般的HTML是不同
    网站PR值
    CommunityServer2.0何去何从?
    网络最经典命令行
    炎热八月,小心"落雪"
    Topology activation failed. Each partition must have at least one index component from the previous topology in the new topology, in the same host.
    SharePoint 2013服务器场设计的一些链接
  • 原文地址:https://www.cnblogs.com/kexiblog/p/10885282.html
Copyright © 2011-2022 走看看