Problem description: Enter an integer and output the number of 1s in the binary representation of the number. Negative numbers are represented by complements.
Idea: Obviously, you can convert a decimal integer to a binary representation string, and then count the number of "1". Of course, it can also be solved by combining the division operation and the remainder operation.
Code:
import org.junit.Test;
public class NumberOf1 {
public int numberOf1(int n) {
String num = Integer.toBinaryString(n);
System.out.println(num);//十进制n的二进制字符串表示
int count = 0;
for(int i = 0;i < num.length();i++)
if(num.charAt(i)=='1')
count++;
return count;
}
@Test
public void test(){
System.out.println(numberOf1(15));
}
}
Output:
1111
4