Integer.toBinaryString()

今天刷到一道题,是这样的:

输入一个整数,输出该数二进制表示中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();
    }
    
}

 

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值