今天刷到一道题,是这样的:
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
想到Java中有一个Integer.toBinaryString(),他的作用是把一个10进制数转为32位的2进制数。同时对负数,会用补码表示。
Returns a string representation of the integer argument as an unsigned integer in base 2.
The unsigned integer value is the argument plus 232 if the argument is negative; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s.
The value of the argument can be recovered from the returned string s by calling Integer
因此这道题的解法可以直接写为:
public class NumberOf1 {
public int NumberOf1(int n) {
return Integer.toBinaryString(n).replaceAll("0", "").length();
}
}