三种方式求: 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示

package com.example;

public class Solution {
/*
* 转化成2进制数计算
*/
public int NumberOf1(int n) {
String string = Integer.toBinaryString(n);
int count = 0;
for (int i = 0;i < string.length();i++) {
if (string.charAt(i) == '1') {
count++;
}
}
return count;
}
/*
* 使用逻辑与运算方法
*/
public int NumberOf2(int n) {
int count = 0;
for (int i = 0; i < Integer.SIZE;i++) {
if ((n & 1) == 1) {
count++;
}
n = n >> 1;
}
return count;
}
/*
* 使用除法进行运算
*/
public int NumberOf3(int n) {
//这里负数因为要用第33位,所以要使用long类型
long L = 1L;
if (n < 0) {
L = (L << 32) + n;
} else {
L = n;
}
int count = 0;
long temp = 0;
while (true) {
temp = 0;
temp = L % 2;
/*
* 遇到余数为1的情况就加一
*/
if (temp == 1) {
count++;
L--;
}
L /= 2;
if (L == 0) {
break;
}
}
return count;
}
public static void main(String [] args) {
Solution solution = new Solution();
int []temp = new int[3];
temp[0] = solution.NumberOf2(-3);
temp[1] = solution.NumberOf2(-3);
temp[2] = solution.NumberOf2(-3);
for (int i =0;i<3;i++) {
System.out.println(temp[i]);
}
}
}

原文地址:https://www.cnblogs.com/adamhome/p/7258492.html