# LintCode181将整数A转换为B

xiaoxiao2021-02-28  1

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

##### 注意事项

Both n and m are 32-bit integers.

(31)10=(11111)2

(14)10=(01110)2

1 2 3 4 5 6 7 8 9 10 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' )

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 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