今天刷到一道题,是这样的:
输入一个整数,输出该数二进制表示中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();
}
}
最后
以上就是淡定钢笔最近收集整理的关于Integer.toBinaryString()的全部内容,更多相关Integer内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复