二进制中1的个数_1513

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

输入:

输入可能包含多个测试样例。
对于每个输入文件,第一行输入一个整数T,代表测试样例的数量。对于每个测试样例输入为一个整数。
。n保证是int范围内的一个整数。

输出:

对应每个测试案例,
输出一个整数,代表输入的那个数中1的个数。

样例输入:
3
4
5
-1
样例输出:
1
2
32
package jiudu;

import java.util.Scanner;
 
public class erjinzhi1geshu_1513 {
    public static void main(String args[]) {
        Scanner input= new Scanner(System.in);
        while (input.hasNext()) {
        	int n=input.nextInt();
        	for(int j=1;j<=n;j++){
        		int a=input.nextInt();
        		String temp=Integer.toBinaryString(a);  
        		int count=0;
        		for(int k=0;k<temp.length();k++){
        			if(temp.charAt(k)=='1')
        				count++;        			
        		}
        		System.out.println(count);        		
        	}
            
        }
    }
}
package jiudu;

import java.util.Scanner;
 
public class erjinzhi1geshu_1513bak {
    public static void main(String args[]) {
        Scanner input= new Scanner(System.in);
        while (input.hasNext()) {
        	int n=input.nextInt();
        	for(int j=1;j<=n;j++){
        		int a=input.nextInt();
        		 int count = getResult(a);
        		System.out.println(count);       		
        	}
            
        }
    }
    
    public static int  getResult(int n)
    {
    	//将数字右移,每进行一次移位就查看最低位的值是否为1,因为int为32bit,所以一共移位32次
    	 int count = 0;
    	 int rightestBit;            // 用于保存n对应二进制数字的最低位
    	 int i = 0;
    	 while(i < 32)
    	 {
    	     rightestBit = 1 & n;   // 用1与n进行按位相与,得到数字n二进制最低位的值
    	     count = count + rightestBit; //最低位的1保持下来,计数
    	     n = n >> 1; // 右移1位,左边补0
    	     i++;
    	 }
    	 return count;
    	}
}

相同的题目有:
<pre name="code" class="html">https://leetcode.com/problems/number-of-1-bits/
解决方案:
<pre name="code" class="java">package jiudu;

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
         	//将数字右移,每进行一次移位就查看最低位的值是否为1,因为int为32bit,所以一共移位32次
    	 int count = 0;
    	 int rightestBit;            // 用于保存n对应二进制数字的最低位
    	 int i = 0;
    	 while(i < 32)
    	 {
    	     rightestBit = 1 & n;   // 用1与n进行按位相与,得到数字n二进制最低位的值
    	     count = count + rightestBit; //最低位的1保持下来,计数
    	     n = n >> 1; // 右移1位,左边补0
    	     i++;
    	 }
    	 return count;
        
    }
}




 
  


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值