LintCode Python 入门级题目 365.二进制有多少个1; 181.将整数A转换为B

原题365描述:

计算在一个 32 位的整数的二进制表式中有多少个 1.

样例

给定 32 (100000),返回 1

给定 5 (101),返回 2

给定 1023 (111111111),返回 9

挑战 

If the integer is n bits with m 1 bits. Can you do it in O(m) time?

原题181描述:

 

如果要将整数A转换为B,需要改变多少个bit位?

 注意事项

Both n and m are 32-bit integers.

样例

如把31转换为14,需要改变2个bit位。

(31)10=(11111)2

(14)10=(01110)2

 

 

题目分析:

 

如两题均为二进制操作,使用python内置函数bin(number)转化为二进制处理

注意题目要求32位二进制表示,需要补0或1。

源码:

 

class Solution:
    # @param num: an integer
    # @return: an integer, the number of ones in num
    def countOnes(self, num):
        # write your code here
        twoStr = bin(num).replace('0b','')
        if twoStr[0] == '-':
            return 32 - twoStr.count('0')
        else:
            return twoStr.count('1')

 

  

class Solution:
    """
    @param a, b: Two integer
    return: An integer
    """
    def bitSwapRequired(self, a, b):
        # write your code here
        if a == b : return 0
        # 负数补1至32位
        if a < 0: 
            strA = bin(a).replace('-0b','')
            strA = (32-len(strA))*'1' + strA
        else: # 整数补0至32位
            strA = bin(a).replace('0b','')
            strA = (32-len(strA))*'0' + strA
        if b < 0: 
            strB = bin(b).replace('-0b','')
            strB = (32-len(strB))*'1' + strB
        else: 
            strB = bin(b).replace('0b','')
            strB = (32-len(strB))*'0' + strB
        
        n = len(strA)
        count = 0
        for i in range(-1,-n-1,-1):
            if strA[i] != strB[i]:
                count += 1
        return count

  

 

转载于:https://www.cnblogs.com/bozhou/p/7007372.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值