Find nth SET bit in an int

后端 未结 11 863
栀梦
栀梦 2020-12-14 18:14

Instead of just the lowest set bit, I want to find the position of the nth lowest set bit. (I\'m NOT talking about value on the nt

11条回答
  •  醉梦人生
    2020-12-14 18:45

    def bitN (l: Long, i: Int) : Long = {
      def bitI (l: Long, i: Int) : Long = 
        if (i == 0) 1L else 
        2 * { 
          if (l % 2 == 0) bitI (l / 2, i) else bitI (l /2, i-1) 
        }
      bitI (l, i) / 2
    }
    

    A recursive method (in scala). Decrement i, the position, if a modulo2 is 1. While returning, multiply by 2. Since the multiplication is invoced as last operation, it is not tail recursive, but since Longs are of known size in advance, the maximum stack is not too big.

    scala> n.toBinaryString.replaceAll ("(.{8})", "$1 ")
    res117: java.lang.String = 10110011 11101110 01011110 01111110 00111101 11100101 11101011 011000
    
    scala> bitN (n, 40) .toBinaryString.replaceAll ("(.{8})", "$1 ")
    res118: java.lang.String = 10000000 00000000 00000000 00000000 00000000 00000000 00000000 000000
    

提交回复
热议问题